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 an Array of strings.

  • The work performed by the callbacks isn’t finished once map() is finished, because await only pauses the surrounding arrow function and httpGet() is resolved asynchronously. That means you can’t use await to wait until downloadContent() 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