What is async/await?
async/await is the ultimate solution to asynchrony based on Promise proposed by ES7.
async
async is a modifier added before the function, and the function defined by async will return a Promise object resolve value by default. Therefore, the async function can be directly then, and the return value is the function passed in by the then method.
// async基础语法
async function fun0(){
console.log(1);
return 1;
}
fun0().then(val=>{
console.log(val) // 1,1
})
async function fun1(){
console.log('Promise');
return new Promise(function(resolve,reject){
resolve('Promise')
})
}
fun1().then(val => {
console.log(val); // Promise Promise
})
await
await is also a modifier and can only be placed within the function defined by async. It can be understood as waiting.
If the object modified by await is a Promise object: the content returned in the Promise (resolve or reject parameters) can be obtained, and the statement will not be executed until the value is obtained;
If not a Promise object: Treat the non-promise as the result of the await expression.
async function fun(){
let a = await 1;
let b = await new Promise((resolve,reject)=>{
setTimeout(function(){
resolve('setTimeout')
},3000)
})
let c = await function(){
return 'function'
}()
console.log(a,b,c)
}
fun(); // 3秒后输出: 1 "setTimeout" "function"
function log(time){
setTimeout(function(){
console.log(time);
return 1;
},time)
}
async function fun(){
let a = await log(1000);
let b = await log(3000);
let c = log(2000);
console.log(a);
console.log(1)
}
fun();
// 立即输出 undefined 1
// 1秒后输出 1000
// 2秒后输出 2000
// 3秒后输出 3000
Correct usage of async/await
// 使用async/await获取成功的结果
// 定义一个异步函数,3秒后才能获取到值(类似操作数据库)
function getSomeThing(){
return new Promise((resolve,reject)=>{
setTimeout(()=>{
resolve('获取成功')
},3000)
})
}
async function test(){
let a = await getSomeThing();
console.log(a)
}
test(); // 3秒后输出:获取成功