setTimeout、Promise、Async/Await 的区别

本文探讨了JavaScript中的同步与异步执行,详细阐述了宏任务与微任务的区别,以及setTimeout、Promise和Async/Await的工作原理。通过实例展示了它们在执行顺序上的特点,如setTimeout属于宏任务,而Promise的then方法和Async/Await后的代码则作为微任务处理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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-->setTimeout

Promise:

Promise本身是同步的,但在执行resolve或者rejects时是异步的,即then方法是异步的。
 console.log("start");
    let promise1 = new Promise(function(resolve) {
        console.log("111");
        resolve();
        console.log("111 end");
    }).then(function(){
        console.log('222');
    })

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

输出:start-->111-->>111end-->end-->222-->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后会立即执行表达式,然后把表达式后边的代码放到微任务队列中,让出执行栈让同步代码先执行;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值