Created
February 23, 2020 20:50
-
-
Save RomainMazB/3f6c59baf474a48f8d1ac60dc9c757a7 to your computer and use it in GitHub Desktop.
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
const max_pending_promises = 3 | |
export default class Queue { | |
static queue = []; | |
static nb_pending_promises = 0; | |
static enqueue (promise) { | |
return new Promise((resolve, reject) => { | |
this.queue.push({ | |
promise, | |
resolve, | |
reject, | |
}); | |
this.dequeue(); | |
}); | |
} | |
static dequeue () { | |
// If max pending promises is reached, return | |
if (this.nb_pending_promises >= max_pending_promises) { | |
return false; | |
} | |
const item = this.queue.shift(); | |
// If all promises are done, return | |
if (!item) { | |
return false; | |
} | |
// Try to perform the next promise | |
try { | |
this.nb_pending_promises++; | |
item.promise() | |
.then((value) => { | |
item.resolve(value); | |
}) | |
.catch(err => { | |
item.reject(err); | |
}) | |
} catch (err) { | |
item.reject(err); | |
} finally { | |
// In all cases: decrement and try to perform the next promise | |
this.nb_pending_promises--; | |
this.dequeue(); | |
} | |
return true; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment