setTimeout、promise、async/await 的区别(转存)

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

宏任务优先级:
主代码块 > setImmediate > MessageChannel > setTimeout / setInterval

微任务优先级:
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

console.log(" script start"); 
        async function async1(){
            await async2()
            console.log("asyncl end")
        } 
        
        async function async2(){
            console.log(" async2 end") 
        }
        async1();
        setTimeout(function(){
            console.log("setTimeout")
        },0)

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

输出顺序: script start -> async2 end ->Promise - ->undefined ->setTimeout
————————————————
版权声明:本文为CSDN博主「wangpachong」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/wangpachong/article/details/116168242

你可能感兴趣的:(setTimeout、promise、async/await 的区别(转存))