关于es6:结合收藏文章-async-await-8张图详解执行顺序总结

3次阅读

共计 1426 个字符,预计需要花费 4 分钟才能阅读完成。

// 1
function axiosGetList() {return new Promise((resolve, reject) => {console.log('axios')
    resolve(true)
  })
}
// 2
async function getList() {const a = await axiosGetList()
  if (a) {console.log('申请胜利')
  }
}
// 执行
c()
// 3
function c() {console.log('c start')
  async function dd() {const a = await getList()
    console.log('a:',a)
  }
  dd()
  console.log('c end')
}
// 4
new Promise((r, j) => {console.log('promise1')
  r() // 如果没有这行,promise2 不会执行}).then(() => {console.log('promise2')
})
// 5
setTimeout(() => {console.log('settimeout')
}, 0)
// 6
console.log('window')



输入后果(谷歌浏览器):

1、c start
2、axios
3、c end
4、promise1
5、window
6、申请胜利
7、promise2
8、a: undefined
9、settimeout

第一步:

进入 c() 执行 console.log('c start')

第二步:

进入 dd() 执行 await getList()
进入 getList() 执行 await axiosGetList()
进入 axiosGetList() 执行 console.log('axios')

第三步:

执行完所有的 await 后
会跳出到第二步 dd() 的中央(也就是第一次执行 await 的函数
先是寻找与它 (dd()) 同级的同步并执行)
console.log('c end'),同级的同步执行完后
会跳到外层去执行同步【这里揭示一下,遇到 await 会先截断前面的程序】

第四步:

执行最外层的 new Promise() 的
console.log('promise1'),此时的 then 函数并不会执行
这里不作形容了

第五步:

执行 console.log('window')
为什么不执行 setTimeout 呢,setTimeout 总是会放在最初面去执行
这里也不作形容了

第六步:

执行完外层的同步后,又会回到调用 await 的中央
回到哪一步呢,就是回到最初有执行 await 的中央
去干什么呢,去执行 then 办法
看到 getList() 办法里,咱们是通过赋值模式去获取的
当然,你也能够写成 then 模式去,换成 then 就是
await axiosGetList().then(() => {console.log('申请胜利') })

第七步:

这时候,await 外面的 then 都执行完了
它又会先跳到外层去寻找异步函数并且去执行它
咱们最外层还有个 then 函数没有执行,就是
console.log('promise2')

第八步:

好了,外部与内部的 then 函数都执行完了
能够安心的走 await 前面的程序了,又回到第一次调用
await 的中央执行它前面的 console.log('a', a)
这里的 a 因为没有接管到返回值,所以为 undefined

第九步:

执行 setTimeout 的 console.log('settimeout')

总结:文章仅是集体总结出的论断,并不保障 100% 正确,学而时习之,温故而知新

正文完
 0