Skip to content

Instantly share code, notes, and snippets.

@joaoneto
Last active June 11, 2020 03:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save joaoneto/5367fee66d3270e44f8c2af3f0127038 to your computer and use it in GitHub Desktop.
Save joaoneto/5367fee66d3270e44f8c2af3f0127038 to your computer and use it in GitHub Desktop.
Javascript example of asynchronous and serial processing flow in async/await reduce function
const mockAsyncProcess = (objToProcess) => {
console.time(objToProcess.id)
console.log(`BEGIN: ${objToProcess.id}`)
return new Promise((resolve) => {
setTimeout(() => {
resolve(`RESULT -> ${objToProcess.id}`);
console.timeEnd(objToProcess.id)
console.log(`END: ${objToProcess.id}`)
}, Math.random() * 1000)
})
}
const seriesOfRawDataToProcess = [
{ id: 1 },
{ id: 2 },
{ id: 3 },
{ id: 4 },
]
;(async () => {
console.log('begin all')
try {
const asyncTransform = async (objToProcess) => {
let result;
try {
result = await mockAsyncProcess(objToProcess)
} catch (err) {
console.log(err)
}
return result
};
const sequentialResult = await seriesOfRawDataToProcess.reduce(async (stack, objToProcess) => {
return [
...await stack,
await asyncTransform(objToProcess),
]
}, [])
console.log('✅', sequentialResult)
} catch (err) {
console.log(err)
}
console.log('end all')
})()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment