繁体   English   中英

如何使用 try/catch 在异步/等待函数中使用 Promise.all

[英]How could I use Promise.all in an Async/Await function using try/catch

我正在努力解决承诺。 到目前为止,我喜欢使用 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'
];

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

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

将每个 URL 映射到fetch调用,并在fetch Promise 上调用.json

 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 });

您可以使用map函数为所有 url 创建 promise 并通过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*/);
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);
  }
}

我遇到了同样的问题,来自 Discord 的一位导师帮助了我。

我相信您是在 Windows 10 上运行它的,而我所做的只是关闭了安全性(在 chrome 的隐私和安全设置中)并且它按预期工作。

注意:请确保在浏览时打开此功能。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM