Async/Await on arrays
Last updated:
arr.forEach()
will not work with async functions
If you need to execute async functions sequentially use for..of
:
async function printFiles () { const files = await getFilePaths();
for (const file of files) { const contents = await fs.readFile(file, 'utf8'); console.log(contents); }}
If you need to execute async functions in parallel use arr.map()
, which returns an array of promises and resolve using Promise.all()
:
async function printFiles () { const files = await getFilePaths();
await Promise.all(files.map(async (file) => { const contents = await fs.readFile(file, 'utf8') console.log(contents) }));}
This will only return successfully if all Promises resolve, it will reject when the first Promise is rejected.
Promise.allSettled()
In situations where we want to proceed even if some of the Promises are rejected (e.g. we are sending multiple async requests were some of them may fail) we should use Promise.allSettled()
. It always returns an array with fullfilled and rejected Promises.
This helper function illustrates how it works. It returns the successful responses and passes the errors to an error handler:
async function allSettled ({promises, errorHandler}) { const all = await Promise.allSettled(promises) return all.reduce((values, p) => { if (p.status === 'fulfilled') { values.push(p.value) } if (p.status === 'rejected') { if (errorHandler) errorHandler(p) } return values }, [])}