在http://jsfiddle.net/,下面这段js可以正常输出一个图片:
fetch('http://fiddle.jshell.net/img/logo.png')
.then(response => response.blob())
.then(myBlob => {
let objectURL = URL.createObjectURL(myBlob);
let image = document.createElement('img');
image.src = objectURL;
document.body.appendChild(image);
})
.catch(e => {
console.log('There has been a problem with your fetch operation: ' + e.message);
});
将Promise修改成await async,结果也是可以的:
async function myFetch() {
let response = await fetch('http://fiddle.jshell.net/img/logo.png');
let myBlob = await response.blob();
let objectURL = URL.createObjectURL(myBlob);
let image = document.createElement('img');
image.src = objectURL;
document.body.appendChild(image);
}
myFetch()
.catch(e => {
console.log('There has been a problem with your fetch operation: ' + e.message);
});
这样写会报错,原因是myfetch返回的是一个Promise:
async function myFetch() {
let response = await fetch('http://fiddle.jshell.net/img/logo.png');
let myBlob = await response.blob();
return myBlob;
}
const myBlob = myFetch();
console.log(myBlob);
let objectURL = URL.createObjectURL(myBlob);
let image = document.createElement('img');
image.src = objectURL;
document.body.appendChild(image);
所以要这样加一次await:
async function myFetch() {
let response = await fetch('http://fiddle.jshell.net/img/logo.png');
let myBlob = await response.blob();
return myBlob;
}
async function main() {
const myBlob =await myFetch();
console.log(myBlob);
let objectURL = URL.createObjectURL(myBlob);
let image = document.createElement('img');
image.src = objectURL;
document.body.appendChild(image);
}
main();
本文介绍了一种使用JavaScript的fetch API结合async/await语法来从远程URL获取图片并将其显示在网页上的方法。同时探讨了如何正确处理返回的Promise,并通过示例代码展示了常见错误及其解决方案。

被折叠的 条评论
为什么被折叠?



