1.3 看懂JavaScript 事件循环和async/await

452 阅读1分钟

别看了,没写完。/

一切的起源只是我想在项目中使用async/await,但是苍天饶过谁,一直失败,所有就此彻底重建认知。网上有个题目对于理解非常有帮助,我就直接拿来用了。👇


    async function async1() {
        console.log( 'async1 start' )
        await async2()
        console.log( 'async1 end' )
    }
    
    async function async2() {
        console.log( 'async2' )
    }
    
    console.log( 'script start' )
    
    setTimeout( function () {
        console.log( 'setTimeout' )
    }, 0 )
    
    async1();
    
    new Promise( function ( resolve ) {
        console.log( 'promise1' )
        resolve();
    } ).then( function () {
        console.log( 'promise2' )
    } )
    
    console.log( 'script end' )

千万别按F12,黏贴代码,一边看文章一边看代码,会high😄

1.3.1 想要找到这道题的正确答案,就得先了解下面三条

  • JavaScript事件循环机制、调用栈以及任务队列
  • promise
  • async await 如果你都能理解,那么就跳过1.3.1这一小节,如果觉得有不理解的,那请继续看下去。

#####1.3.1.1 JavaScript事件循环机制、调用栈以及任务队列(也叫回调队列)

  • 首先JavaScript时单线程的,也就是一次只能执行一个任务
  • 任务又可以分为同步任务和异步任务 看代码
console.log(1);
setTimeout(function(){console.log(2);}, 0);
console.log(3);

这会输出什么?1,3,2为什么?看下图

  1. 先执行console.log('1'),console.log(1);入栈 console.log(1)执行完毕从栈顶出栈

    image.png

  2. 执行setTimeout(function(){console.log(2);}, 0); 发现这是异步任务,先放在一旁,就放在其他模块好了,在其他模块中,0秒后执行完毕就进入任务队列等待进入调用栈

    image.png

  3. 执行console.log(3); console.log(3);入栈 console.log(3)执行完毕从栈顶出栈

    image.png

  4. 执行setTimeout(function(){console.log(2);}, 0);同样是入栈执行结束后出栈

image.png
这就是JavaScript事件循环机制、调用栈以及任务队列,很容易理解吧? #####1.3.1.2 下面该promise出场了

promise segmentfault.com/a/119000001… segmentfault.com/a/119000000… es6.ruanyifeng.com/#docs/promi… segmentfault.com/a/119000001… blog.csdn.net/corner2030/… segmentfault.com/a/119000001…