async关键字
将 async 关键字加到函数申明中,可以告诉它们返回的是 promise,而不是直接返回值。
示例
let hello = async function() { return "Hello" };
hello();
要实际使用promise完成时返回的值,我们可以使用.then()块,因为它返回的是 promise:hello().then((value) => console.log(value))
甚至只是简写如hello().then(console.log)
await关键字
当 await 关键字与异步函数一起使用时,它的真正优势就变得明显了 —— 事实上, await 只在异步函数里面才起作用。它可以放在任何异步的,基于 promise 的函数之前。它会暂停代码在该行上,直到 promise 完成,然后返回结果值。在暂停的同时,其他正在等待执行的代码就有机会执行了。
示例
async function hello() {
return greeting = await Promise.resolve("Hello");
};
hello().then(alert);
使用async和await重写Promise代码
fetch('coffee.jpg')
.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);
});
让我们将其转换为使用async / await看看它使事情变得简单了多少:
async function myFetch() {
let response = await fetch('coffee.jpg');
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);
});
由于 async 关键字将函数转换为 promise,可以重构以上代码 —— 使用 promise 和 await 的混合方式,将函数的后半部分抽取到新代码块中。
async function myFetch() {
let response = await fetch('coffee.jpg');
return await response.blob();
}
myFetch().then((blob) => {
let objectURL = URL.createObjectURL(blob);
let image = document.createElement('img');
image.src = objectURL;
document.body.appendChild(image);
});