Last active
May 2, 2022 22:42
-
-
Save tombigel/6b76587774603934be3f1f6254706ea3 to your computer and use it in GitHub Desktop.
Promise 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
/** | |
* @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