一、async的用法
async
用于声明异步函数它以类似同步的方式来写异步方法,语法与声明函数类似:
async function fun(){
return "Hello Word!";
}
他的调用与函数相同:
async function fn(){
return "Hello Word!";
}
console.log(fn());
async
的返回结果是一个Promise
对象,如果 return
的值是除Promise
以外的任何值,都算是成功的,都会调用Promise.resolve()
方法,所以他的输出结果为:
如果返回的值是Promise
或者错误,都会调用 Promise.reject()
方法:
async function fn(){
return new Promise((resolve,reject) => {
reject('Error');
})
}
或者
async function fn(){
throw new Error('rejected');
}
console.log(fn());
结果为:
与
要获取 async
函数的返回结果,就需要用到 Promise
的 then
或 catch
来获取
then
获取成功的结果:
async function fn(){
return "Hello Word!";
}
fn().then(data => console.log(data));
结果:
catch
获取失败的结果:
async function fn(){
throw new Error('rejected');
}
fn().catch(data => console.log(data));
结果:
如果async
函数调用时注册了回调函数,那么注册的回调函数就会被放到异步队列
中,主线程会先执行下面的代码,再回来执行async
函数:
async function fn(){
return "Hello Word!";
}
fn().then(data => console.log(data));
console.log("1");
console.log("2");
console.log("3");
console.log("4");
console.log("5");
结果:
不注册回调函数:
async function fn(){
console.log("Hello Word!");
}
fn();
console.log("1");
console.log("2");
console.log("3");
console.log("4");
console.log("5");
结果:
所以,async 函数与普通函数的使用并无区别,唯一的区别就是返回值是 Promise 对象
二、await 的用法
await
函数只能放到 async
函数里面。
await
右侧的表达式一般为Promise
对象,也可以是其他值。- 如果是
Promise
对象,await
返回的是Promise
成功的值。 - 是其他值,就直接将此值作为
await
的返回值。
注意
await
必须写在async
函数中,但async
函数可以没有await
- 如果
await
的Promise
失败了,就会抛出异常,需要通过try...catch
捕获处理
执行顺序
如果同步代码与异步代码同时出现,一定是先执行同步代码
function fn1(){
return "1";
}
async function fn2(){
return "2";
}
async function fn(){
let a = await fn1();
console.log("3");
let b = await fn2();
console.log(a,b);
console.log("4");
}
fn();
console.log("5");
输出结果为:
代码的执行过程:
调用 fn() 函数,遇到 await 执行异步操作,先执行同步中的console.log(“5”);执行完毕后回来继续执行异步,输出1,然后输出3,遇到 await 执行异步并且阻断后续执行,执行完毕后输出1 2,最后输出4