Skip to content

Instantly share code, notes, and snippets.

@Aaronius
Last active September 15, 2017 11:54
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save Aaronius/fdb06370a6a67dc4f726 to your computer and use it in GitHub Desktop.
Save Aaronius/fdb06370a6a67dc4f726 to your computer and use it in GitHub Desktop.
Promise-based Sequential Queue
// Queues multiple asynchronous processes to run sequentially via promises
// Process can be added to the queue while other processes are running
var Sequence = function() {};
Sequence.prototype.enqueue = function(fn) {
this.tail = this.tail ? this.tail.finally(fn) : fn();
};
// Usage
var sequence = new Sequence();
sequence.enqueue(function() {
var deferred = $q.defer();
// do some async stuff
deferred.resolve();
return deferred.promise;
});
sequence.enqueue(function() {
return doSomethingAsyncThatReturnsAPromise();
});
@twaldecker
Copy link

That's a nice idea, how do you use it? What happens when the last promise is fulfilled, are new enqueued items called directly? Does it all work even with then instead of finally?

I'm not expecting you to answer all these questions, just saving my questions for future use.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment