javascript - 我如何在使用 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 获取数据的方法是什么?
解决方案
将每个 URL 映射到一个fetch
调用,并调用.json
Promise 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
});
推荐阅读
- push-notification - Gatsby + Netlify 添加推送通知
- python - 如何创建两个注册系统?
- angular - 带有@Host参数的单元测试Angular 9组件无法解析参数
- azure-data-factory - 如何调试 DataFlow 异常
- django - 我在哪里可以保存可重用应用程序的设置数据
- azure-cognitive-search - 将 Azure SQL DB 数据自动同步到 Azure 搜索索引
- python - 为什么我不能在 tkinter 画布中绘制 numpy 矩阵?
- android - 如何旋转 TextView 而不仅仅是它的文本
- javascript - 控制台错误无法解构“el.position(...)”的属性“top”,因为它未定义。WordPress jQuery
- java - 在 Netty 中,我想验证证书是否由 CA 颁发