Created
May 4, 2021 10:24
-
-
Save EmilienD/2047442d3a86ac4a792218fce22ca62c to your computer and use it in GitHub Desktop.
simple promise queue to execute promises consecutively
This file contains hidden or 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
| 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