Last active
September 15, 2017 11:54
Promise-based Sequential Queue
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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(); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.