我目前正在学习async await fetch
我创建了以下示例来帮助我学习。
下面的工作示例:
- 从公共 API 获取三个随机 json 记录
- 提取出
url
从每次返回json
- 创建三个
img
元素
- 追加三
img
文档正文的元素。
请注意promise2
故意设置了错误的路径以强制出现 http 状态 404。
如果这三个承诺中的任何一个发生此错误,我该如何处理?
// 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 您可以并行运行所有 fetch 调用并等待它们全部完成。
const test = async() => {
const promise1 = await fetch('https://dummyimage.com/48x48/4caf50/ffffff.jpg&text=.jpg')
.then(r => r.url)
const promise2 = await fetch('https://dummyimage.com/bad/url/here/48x48/e91e63/ffffff.png&text=.png')
.then(r => r.url)
const promise3 = await fetch('https://dummyimage.com/48x48/00bcd4/ffffff.gif&text=.gif')
.then(r => r.url)
const results = await Promise.allSettled([promise1, promise2, promise3])
console.log(results);
}
test();
对于较旧的支持,您需要使用一个承诺来捕获提取中的任何错误。
function makeCall () {
return new Promise((resolve) => {
fetch('https://dummyimage.com/48x48/4caf50/ffffff.jpg&text=.jpg')
.then(r => console.log(r.url))
.catch(error => resolve({ error }))
})
}
const test = async() => {
const promise1 = makeCall()
const promise2 = makeCall()
const promise3 = makeCall()
const results = await Promise.all([promise1, promise2, promise3])
console.log(results)
}
test()
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)