【发布时间】:2020-09-13 14:00:32
【问题描述】:
我目前正在学习async await fetch,我创建了以下示例来帮助我学习。
下面的工作示例:
- 从公共 API 获取三个随机 json 记录
- 从每个返回
json中提取url - 创建三个
img元素 - 将三个
img元素附加到文档正文。
请注意,promise2 故意设置了错误的路径来强制 http 状态为 404。
如果三个promise中的任何一个都发生了这个错误,我该如何处理?
// the big promise.
async function getAsyncData() {
try {
// attempt to resolve 3 individual unrelated promises...
let promise1 = await fetch('https://dummyimage.com/48x48/4caf50/ffffff.jpg&text=.jpg');
let promise2 = await fetch('https://dummyimage.com/bad/url/here/48x48/e91e63/ffffff.png&text=.png');
let promise3 = await fetch('https://dummyimage.com/48x48/00bcd4/ffffff.gif&text=.gif');
// we create an html img element and set its src attribute to the thumbnailUrl...
var img = document.createElement('img');
img.src = promise1.url;
// ...and add it to our html document body...
document.body.append(img);
// we create an html img element and set its src attribute to the thumbnailUrl...
var img = document.createElement('img');
img.src = promise2.url;
// ...and add it to our html document body...
document.body.append(img);
// we create an html img element and set its src attribute to the thumbnailUrl...
var img = document.createElement('img');
img.src = promise3.url;
// ...and add it to our html document body...
document.body.append(img);
} catch (error) {
console.log('Try/Catch block error:', error);
}
// return {
// }
}
getAsyncData();
【问题讨论】:
-
试试
Promise.allSettled。在只有一个 promise 拒绝的情况下,它不会拒绝所有内容(Promise.all会这样做)。另一个注意事项是,如果您按照示例中的方式使用await,则您的fetches 不能并行。 -
我明白了。好的。至于
fetch无法并行……啊! Youtube 示例...你是在提议我awaitfetch然后awaitjsonfetch吗? -
更新了代码以反映我认为您的意思。
-
@suchislife,将 Promises 构建成一个数组,并使用 for await 循环来迭代 Promises。这样你就可以两全其美(取决于你想要做什么)
-
我在 FF 68 上,它不支持
allSettled。我会将所有fetches 放入一个数组并在那里使用它们。可以将 Promises 和 async/await 混合使用。这一切都与易用性有关,并试图避免回调地狱。它让我们可以编写同步 looking 代码。
标签: javascript promise async-await