谈谈setTimeout、Promise、Async/Await 的区别

  1. 首先我们谈谈Event Loop:
    setTimeout是一个macro任务
    promise、和await后续为micro任务
    所以在执行顺序上会先进行同步代码,再者Promise、Async/Await,最好setTimeout。

  2. 谈谈Promise、Async/Await差异
    promise是resolve为异步方法,将放入微任务队里里执行,但是resolve前后的正常代码为同步代码;Async/Await会返回一个promise,await 的顺序是从右往左的,也就是说await 右边的方法也优先执行同步代码,再让出线程,进入微任务队列,await下面的代码可以理解为promise then里面的代码。
    下面是一个网上比较火的题:

 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' )

chrome下面的打印:具体可以仔细看看event loop的执行顺序,当然node下面会不一样,因为机制不一样;
在这里插入图片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章