async和await关键字常用于需要获取接口返回值,从而进行后续处理的情况。
一、async关键字的用法
async关键字放在函数前面,用于说明这是一个异步函数,不会阻塞后面代码的执行。
同步代码执行:
//正常情况下JS代码从上到下依次执行,按循序执行
console.log(1);
console.log(2);
//输出结果为:先执行log函数输出1,然后输出2,从上向下依次执行
function log(){
return 1
}
console.log(log());
console.log(2);
通过async关键字声明函数是异步的:
//async表示函数是异步的,然后返回一个promise对象
async function log(){
return 1
}
// 如果async函数中有返回值,当调用该函数时,内部会调用Promise.resolve()方法把它转化成一个promise对象作为返回
//如果没有返回值,则默认返回undefined
//会发现输出的并不是1,而是一个promise对象
// Promise { 1 }
console.log(log());
// 输出2,表示async不会阻塞函数的执行
console.log(2);
获取Promise的结果需要通过.then来获取:
async function log(){
return 1
}
// 通过.then获取promise的值
//会先输出2然后输出1
log().then(res=>console.log(res))
console.log(2);
二、await关键字的用法
await是等待的意思,那他到底在等什么?await关键字只能在async内使用。
在上面我们通过async返回了一个Promise对象并通过.then获取到了返回值,但发现,会先输出2,然后输出1,但在项目中,我们通常需要等待接口返回后,根据返回值,进行对应处理,那我们需要怎样处理才能“等待”返回值后进行后续代码的执行呢?
async function test(){
//需要获取到接口返回值后,根据值进行判断处理
let status = await getDataList()
console.log(status);
console.log(2);
}
//我是一个获取数据列表的接口
function getDataList(){
return new Promise((resolve,rej)=>{
resolve(1)
})
}
//执行方法,等待getDataList方法执行完成后继续向下执行,先输出1后输出2
test()