Skip to content

Instantly share code, notes, and snippets.

@attila
Created February 1, 2019 14:51
Show Gist options
  • Save attila/25c91cdc484d9c46107017a6743746c6 to your computer and use it in GitHub Desktop.
Save attila/25c91cdc484d9c46107017a6743746c6 to your computer and use it in GitHub Desktop.
Sequence asynchronous computations
/**
* 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