Created
February 1, 2019 14:51
-
-
Save attila/25c91cdc484d9c46107017a6743746c6 to your computer and use it in GitHub Desktop.
Sequence asynchronous computations
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
/** | |
* Run asynchronous computations sequentially | |
* | |
* @param {Function} f computation | |
* @returns {function(*): *} | |
*/ | |
const sequence = f => entries => | |
entries.reduce( | |
(promise, entry) => | |
promise.then( | |
() => | |
new Promise(async (resolve, reject) => { | |
try { | |
const result = await f(entry); | |
resolve(entry) | |
} catch (err) { | |
reject(err) | |
} | |
}) | |
), | |
Promise.resolve() | |
); | |
const asyncOp = item => new Promise((resolve, reject) => { | |
setTimeout(() => { | |
resolve(item.id); | |
}, 250) | |
}) | |
const list = [ | |
{ id: 1 }, | |
{ id: 2 }, | |
{ id: 3 }, | |
{ id: 4 } | |
] | |
const asyncOpInOrder = sequence(asyncOp); | |
const runIt = async () => { | |
console.log('+ startup') | |
try { | |
await asyncOpInOrder(list); | |
} catch(err) { | |
console.error('++ failed because', err) | |
} | |
console.log('+ finished processing') | |
} | |
runIt() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment