Promise的四个相关面试题

本文详细分析了JavaScript中的宏队列与微队列机制,通过四个实例展示了setTimeout、Promise、MutationObserver等异步操作的执行顺序。深入理解这一机制对于优化JavaScript代码的执行效率至关重要。
摘要由CSDN通过智能技术生成

宏队列:dom事件回调、ajax事件回调、定时器回调

微队列:promise回调、mutation回调

如对上述名词有不理解之处,请自行上MDN官方文档查询

为了方便起见,代码行由最终的输出指定,如1代表第二行代码,2代表第五行代码。

第一题

setTimeout(() => {
    console.log(1);
}, 0)
Promise.resolve().then(() => {
    console.log(2);
})
Promise.resolve().then(() => {
    console.log(4);
})
console.log(3);

解析:promise为微队列,setTimeOut为宏队列,均为异步。先执行同步调用的最后一行代码。再执行2、4,最后执行1。

所以对应的执行顺序为:3、2、4、1


第二题

setTimeout(() => {
    console.log(1);
}, 0)
new Promise((resolve) => {
    console.log(2);
    resolve()
}).then(() => {
    console.log(3);
}).then(() => {
    console.log(4);
})
console.log(5);

分析:

宏队列:[1]

微队列:[3、4]

同步执行:[2、5]

所以对应的执行顺序为:2、5、3、4、1


第三题

const first = () => (new Promise((resolve, reject) => {
    console.log(3);
    let p = new Promise((resolve, reject) => {
        console.log(7);
        setTimeout(() => {
            console.log(5);
            resolve(6)
        }, 0);
        resolve(1)
    })
    resolve(2)
    p.then((arg) => {
        console.log(arg);
    })
}))

first().then((arg) => {
    console.log(arg);
})
console.log(4);

分析:

宏队列:[5]

微队列:[1、2]

同步执行:[3、7、4]

所以对应的执行顺序为:3、7、4、1、2、5


第四题

setTimeout(() => {
    console.log("0");
}, 0);
new Promise((resolve, reject) => {
    console.log("1");
    resolve()
}).then(() => {
    console.log("2");
    new Promise((resolve, reject) => {
        console.log("3");
        resolve()
    }).then(() => {
        console.log("4");
    }).then(() => {
        console.log("5");
    })
}).then(() => {
    console.log("6");
})

new Promise((resolve, reject) => {
    console.log("7");
    resolve()
}).then(() => {
    console.log("8");
})

分析:

宏队列:[0]

微队列:[2、3、8、4、6、5]

同步执行:[1、7]

所以对应的执行顺序为1、7、2、3、8、4、6、5、0

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值