07. Async Callbacks
One limitation of async
functions is that await
only affects the directly surrounding async function.
Will return array of Promises:
async function downloadContent(urls) {
return urls.map(async url => {
const content = await httpGet(url);
return content;
});
}
There are two issues with this code:
The result is now an
Array
of Promises, not anArray
of strings.The work performed by the callbacks isn’t finished once
map()
is finished, becauseawait
only pauses the surrounding arrow function andhttpGet()
is resolved asynchronously. That means you can’t useawait
to wait untildownloadContent()
is finished.
We can fix both issues via Promise.all()
. We also may remove all unnecessary await
:
async function downloadContent(urls) {
const promiseArray = urls.map(url => httpGet(url));
return await Promise.all(promiseArray);
}
Last updated
Was this helpful?