Skip to content

Instantly share code, notes, and snippets.

@EmilienD
Created May 4, 2021 10:24
Show Gist options
  • Select an option

  • Save EmilienD/2047442d3a86ac4a792218fce22ca62c to your computer and use it in GitHub Desktop.

Select an option

Save EmilienD/2047442d3a86ac4a792218fce22ca62c to your computer and use it in GitHub Desktop.
simple promise queue to execute promises consecutively
function createQueue() {
const queue = [];
let pendingPromise = false;
function enqueue(callback) {
queue.push(callback);
dequeue();
}
function dequeue() {
if (pendingPromise) {
return false;
}
const callback = queue.shift();
if (!callback) {
return false;
}
try {
pendingPromise = true;
callback().finally(() => {
pendingPromise = false;
dequeue();
});
} catch (err) {
pendingPromise = false;
dequeue();
throw err;
}
return true;
}
return { enqueue, dequeue };
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment