Created
January 21, 2019 18:30
-
-
Save gilesbradshaw/2e6e9fc40b3ca1fa35f4d5f9d460aec3 to your computer and use it in GitHub Desktop.
use promises to serialise access to an action
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
// serialises access to an action | |
export default () => { | |
// promise to allow the next action | |
let next = Promise.resolve() | |
return (action) => { | |
let nextResolve | |
const nextNext = () => new Promise( | |
(resolve, reject) => | |
action() | |
.then( | |
(x) => { | |
resolve(x) | |
// allow next action | |
nextResolve() | |
}, | |
) | |
.catch(reject), | |
) | |
const myNext = next | |
next = new Promise( | |
(resolve) => { | |
nextResolve = resolve | |
}, | |
) | |
return myNext | |
.then(nextNext) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment