async await 是es7里面的新语法、它的作用就是 async 用于申明一个 function 是异步的,而 await 用于等待一个异步方法执行完成。它可以很好的替代Promise 中的then
async函数返回一个 Promise 对象,可以使用then方法添加回调函数。当函数执行的时候,一旦遇到await就会先返回,等到异步操作完成,再接着执行函数体内后面的语句。
一、基础使用
async函数返回的是一个Promise对象,这一点极其重要,可以使用then方法添加回调函数,当函数执行的时候,一旦遇到await就会先返回,等到异步结束之后,再接着执行函数体内之后的操作。
async function fn() {
return "hello";
}
fn().then(value => {
console.log(value);
}).catch((err) => {
// console.log('打印出错误');
console.log(err)
})
二、函数多种声明形式对应应用
// 函数声明
async function foo() {}
// 函数表达式
const foo = async function () {};
// 对象的方法
let obj = { async foo() {} };
obj.foo().then(...)
// Class 的方法
class Storage {
constructor() {
this.cachePromise = caches.open('avatars');
}
async getAvatar(name) {
const cache = await this.cachePromise;
return cache.match(`/avatars/${name}.jpg`);
}
}
const storage = new Storage();
storage.getAvatar('jake').then(…);
// 箭头函数
const foo = async () => {};
三、测试
async function timeout(ms) { await new Promise((resolve) => { setTimeout(resolve, ms); console.log(1); }); } async function asyncPrint(value, ms) { await timeout(ms); console.log(value) } asyncPrint('Hello', 100)
结果:
async function fn() { await new Promise((resolve, reject) => { reject('出错了~'); }) } fn().then((val) => { console.log(val) }).catch((err) => { console.log(err) })
结果:
![]()