1. console.log('script start')
    2. async function async1() {
    3. await async2()
    4. console.log('async1 end')
    5. }
    6. async function async2() {
    7. console.log('async2 end')
    8. }
    9. async1()
    10. setTimeout(function() {
    11. console.log('setTimeout')
    12. }, 0)
    13. new Promise(resolve => {
    14. console.log('Promise')
    15. resolve()
    16. })
    17. .then(function() {
    18. console.log('promise1')
    19. })
    20. .then(function() {
    21. console.log('promise2')
    22. })
    23. console.log('script end')
    • 第 1 行是同步代码,输出 script start
    • 第 10 行执行 async1,async1 中执行 async2,因此会输出 async2 end 。然后回到 async1,碰到 await 之后,暂停执行 async 1 中的代码,并将其中执行的代码扔进 job queue 中等待执行。
    • 执行 12 行的 setTimeout,将其函数扔进 callback queue 中等待执行。
    • 执行 16 行新建一个 Promise 对象,输出 Promise ,遇到 resolve() 之后,将后面两个 then 的函数扔进 job queue 中。
    • 27 行中输出 script end

    经过上面的步骤,已经输出的内容有 script start => async2 end => Promise => script end。

    之后处理 job queue 中的函数,job queue 中的需要处理的代码有

    1. aync1 中的代码 console.log('async1 end')
    2. 两个 then 函数的回调。

    另外 callback queue 中含有的代码时:

    1. setTimeout 中的回调函数。

    因此之后的输出内容将会是 async1 end => promise1 => promise2 => script end。

    因此将所有的数据结果结合起来,得到的将会是

    1. // script start => async2 end => Promise => script end => script start
    2. // => async2 end => Promise => script end