什么是async和await?
async 定义异步函数
返回值是promise对象
当调用异步函数时,函数返回值会被resolve处理
出错也会被捕获到
异步函数内部可以使用await
await 暂停异步函数的执行
当使用在promise 前面是,await等待promise完成,并返回promise的结果
await只能写在async函数里面,
await只能和promise一起使用,不能和callback一起使用
await关键字后面可以跟任意表达式 如果是promise对象,会等promise执行完在执行下面的代码
async和await的使用
为了解决 promise 中的.then 链 也就是回调地狱
原始写法
function test(n) {
return new Promise(resolve => {
setTimeout(() => resolve(n + 100), n);
});
}
function set1(n) {
console.log(`set1 with ${n}`);
return test(n);
}
function set2(n) {
console.log(`set2 with ${n}`);
return test(n);
}
function set3(n) {
console.log(`set3 with ${n}`);
return test(n);
}
promise写法
function test() {
console.log(111);
const time1 = 100;
set1(time1)
.then(time2 => set2(time2))
.then(time3 => set3(time3))
.then(result => {
console.log(222);
console.log(333);
});
}
test();
async/await写法
async function test() {
console.log(111);
const time1 = 100;
const time2 = await set1(time1);
const time3 = await set2(time2);
const result = await set3(time3);
console.log(222);
console.log(333);
}
test();