setTimeout、promise、async/await 的区别

setTimeout、promise、async/await 的区别

setTimeout属性宏任务,Promise里面的then方法属于微任务,Async/Await中await语法后面紧跟的表达式是同步的,但接下来的代码是异步的,属于微任务。

宏任务优先级:

主代码块 > setImmediate > MessageChannel > setTimeout / setInterval

微任务优先级

微任务microtask:process.nextTick > Promise = MutationObserver

setTimeout

console.log("script start");
   setTimeout(function () {
       console.log('setTimeout')
   }, 0);
   console.log('script end');
  

输出script start -> script end -> set

Promise:

Promise本身是同步的,但在执行resolve或者rejects时是异步的,即then方法是异步的。

   console.log("script start");
    let promise1 = new Promise(function(resolve) {
        console.log("promise1");
        resolve();
        console.log("promise1 end");
    }).then(function(){
        console.log('promise2');
    })

    setTimeout(function () {
        console.log('setTimeout');
    }, 0)
    console.log('script end');

输出顺序: script start -> promise1 -> promise1 end -> script end -> promise2 ->setTimeout

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');
    async1();
    console.log('script end')

输出顺序:script start -> async1 start -> async2 -> script end -> async1 end

async 函数返回一个 Promise 对象,当函数执行的时候,一旦遇到 await 就会先返回,等到触发的异步操作完成,再执行函数体内后面的语句。可以理解为,是让出了线程,跳出了 async 函数体。

await后面跟一个表达式,async方法执行时,遇到await后会立即执行表达式,然后把表达式后边的代码放到微任务队列中,让出执行栈让同步代码先执行;

setTimeout


 console.log("script start");
    setTimeout(function () {
        console.log('setTimeout')
    }, 0);
    console.log('script end');

输出顺序: script start -> script end -> setTimeout

你可能感兴趣的:(js,vue,javascript,html5,es6)