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池
中,并不会阻塞执行
常见问题FAQ
- 免费下载或者VIP会员专享资源能否直接商用?
- 本站所有资源版权均属于原作者所有,这里所提供资源均只能用于参考学习用,请勿直接商用。若由于商用引起版权纠纷,一切责任均由使用者承担。更多说明请参考 VIP介绍。
- 提示下载完但解压或打开不了?
- 找不到素材资源介绍文章里的示例图片?
- 模板不会安装或需要功能定制以及二次开发?
发表评论
还没有评论,快来抢沙发吧!