Last active
June 11, 2020 03:38
-
-
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
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
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