Skip to content

Instantly share code, notes, and snippets.

@RomainMazB
Created February 23, 2020 20:50
Show Gist options
  • Save RomainMazB/3f6c59baf474a48f8d1ac60dc9c757a7 to your computer and use it in GitHub Desktop.
Save RomainMazB/3f6c59baf474a48f8d1ac60dc9c757a7 to your computer and use it in GitHub Desktop.
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