amatiasq
9/22/2014 - 11:33 AM

This function will prevent a long operation to be executed twice in parallel. If the function is invoked a second time before the first time

This function will prevent a long operation to be executed twice in parallel. If the function is invoked a second time before the first time has completed it will receive the same promise from the first invocation without need to invoke the operation again.

function throttlePromise(operation) {
  var promise = null;

  return function() {
    if (!promise) {
      promise = operation.apply(this, arguments).finally(function() {
        promise = null;
      });
    }

    return promise;
  };
}
var getUserData = throttlePromise(function() {
  return AJAX.get('/user-data');
});

getUserData();
getUserData();
getUserData();
getUserData();
getUserData();
getUserData();
getUserData()
// only one ajax call will be executed until here

.then(function() {
  // the previous invocation is complete so this will fire another ajax call
  getUserData();
});