async
顾名思义,就是将一个普通函数声明为异步函数,此函数不管有没有返回值,总会返回一个promise
对象,所以你可以像普通函数一样去调用
async function testAsync () {
console.log('testAsync end')
}
testAsync ().then(res => {
/**
* 1. async 有返回值则res有值
* 2. async 无返回值则res为undefined
*/
console.log(res)
})
await
顾名思义就是等待,具体等待什么,就是等待右侧执行的结果,如果是promise
,则会等待promise
执行完毕才会执行剩下的代码
function promiseFn () {
// eslint-disable-next-line no-new
new Promise((resolve, reject) => {
resolve('promiseFn')
})
}
function promiseFnCb () {
return new Promise((resolve, reject) => {
resolve('promiseFnCb')
})
}
async function testAsync2 () {
console.log('--------------- testAsync2 start ---------------')
const fn1 = await promiseFn()
console.log(fn1)
const fn2 = await promiseFnCb()
console.log(fn2)
console.log('--------------- testAsync2 end ---------------')
}
testAsync2()
/**
* 执行结果
* 1. --------------- testAsync1 start ---------------
* 2. undefined 因为await的函数没有返回值
* 3. promiseFnCb
* 4. --------------- testAsync1 end ---------------
*/
总结
await
只能存在于async
中await
不能存在于循环体内await
只会等待promise
的执行(不管等待的函数有没有返回promise,包含即可)await
遇到setTimeout
、setInterval
...等等,不会等待,而是和js执行栈
一样,放入event池
中,并不会阻塞执行