我如何使用try / catch在Async / Await函数中使用Promise.all

问题描述 投票:0回答:3

我正在努力兑现承诺。到目前为止,我个人喜欢使用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 / await,Promise.all和try / catch块从这些url中获取数据的方法是什么?

javascript ecmascript-6
3个回答
1
投票

将每个URL映射到fetch调用,然后在.json承诺中调用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
  });

0
投票

您可以使用map功能为所有网址创建承诺,然后通过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'
]; 

const promises = starWars.map(url => fetch(url).then(res => res.json());

Promise.all(promises).then(results => /*Resolved code*/)
                     .catch(error => /*Rejected code*/);

0
投票
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'
];

async function makeApiCalls() {
  try {
    let res = await Promise.all(starWars.map(endpoint => fetch(endpoint)));
    // depending on content-type apply .json() .blob() etc
    console.log(response);
  } catch (err) {
    console.error(err);
  }
}

© www.soinside.com 2019 - 2024. All rights reserved.