首页 > 解决方案 > 我如何在使用 try/catch 的 Async/Await 函数中使用 Promise.all

问题描述

我正在努力理解承诺。到目前为止,我喜欢使用 async/await 和 try/catch 块,因为它对我个人来说是可读的。

但是我坚持使用Promise.all这个。

这是我用于练习的数据。

const starWars = [
  'https://swapi.co/api/people/1',
  'https://swapi.co/api/people/2',
  'https://swapi.co/api/people/3',
  'https://swapi.co/api/people/4'
];

我觉得我必须.map()在 async 函数中使用,但是不断遇到错误。

所以我的问题是。使用 async/await、Promise.all 和 try/catch 块从这些 url 获取数据的方法是什么?

标签: javascriptecmascript-6

解决方案


将每个 URL 映射到一个fetch调用,并调用.jsonPromise fetch

const urls = [
  'https://swapi.co/api/people/1',
  'https://swapi.co/api/people/2',
  'https://swapi.co/api/people/3',
  'https://swapi.co/api/people/4'
];

(async () => {
  try {
    const allResponses = await Promise.all(
      urls.map(url => fetch(url).then(res => res.json()))
    );
    console.log(allResponses[0]);
  } catch(e) {
    console.log(e);
    // handle errors
  }
})();

我更喜欢在函数之外捕捉,我认为它看起来更干净并且需要更少的缩进:

const urls = [
  'https://swapi.co/api/people/1',
  'https://swapi.co/api/people/2',
  'https://swapi.co/api/people/3',
  'https://swapi.co/api/people/4'
];

(async () => {
  const allResponses = await Promise.all(
    urls.map(url => fetch(url).then(res => res.json()))
  );
  console.log(allResponses[0]);
  // do stuff with allResponses
})()
  .catch((e) => {
    console.log(e);
    // handle errors
  });

如果您只有一个地方需要等待 Promise 解决,您也可以考虑async完全放弃该功能(这看起来会更好 IMO):

const urls = [
  'https://swapi.co/api/people/1',
  'https://swapi.co/api/people/2',
  'https://swapi.co/api/people/3',
  'https://swapi.co/api/people/4'
];

Promise.all(
  urls.map(url => fetch(url).then(res => res.json()))
)
  .then((allResponses) => {
    console.log(allResponses[0]);
    // do stuff with allResponses
  })
  .catch((e) => {
    console.log(e);
    // handle errors
  });


推荐阅读