Skip to content

Instantly share code, notes, and snippets.

@joaoneto

joaoneto/async-serial.js

Last active Jun 11, 2020
Embed
What would you like to do?
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
You can’t perform that action at this time.