Skip to content

Instantly share code, notes, and snippets.

@tombigel
Last active May 2, 2022 22:42
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tombigel/6b76587774603934be3f1f6254706ea3 to your computer and use it in GitHub Desktop.
Save tombigel/6b76587774603934be3f1f6254706ea3 to your computer and use it in GitHub Desktop.
Promise Queue
/**
* @class PromiseQueue Manage a queue of promises
*/
function PromiseQueue() {
const queue = {};
let idCount = 0;
return {
/**
* Add a promise to the queue and remove it once resolved
* todo: handle reject()
* @param {Promise} promise
* @returns {string} id a unique id of a promise so you could get or remove it manually
*/
add(promise) {
const id = `promise_${idCount++}`;
queue[id] = promise;
console.log('PromiseQueue.add', Object.keys(queue));
promise
.then(() => this.remove(id))
.catch(() => this.remove(id));
return id;
},
/**
* Remove a promise from the queue by id
* @param {string} id
*/
remove(id) {
delete queue[id];
console.log('PromiseQueue.remove', Object.keys(queue));
},
/**
* Get a promise from the queue
* @param {string} id
* @returns {Promise|undefined}
*/
get(id) {
return queue[id];
},
/**
* Invoke a function when all the promises in the queue are resolved or rejected
* @param {function} onResolve
* @param {function} [onReject] silent fail if not defined
* @returns {Promise}
*/
then(onResolve, onReject = () => {}) {
return Promise.all(Object.values(queue))
.then(onResolve)
.catch(onReject);
}
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment