宏任务与微任务

128 阅读1分钟

规则

1、微任务,包括:setTimeout,setInterval、setImmediate
2、宏任务,包括:原生Promise、process.nextTick
3、执行规则
3.1 执行同步任务
3.2 执行微任务队列
3.3 执行宏任务队列

示例

1、题目

console.log('1');

setTimeout(function() {
    console.log('2');
    process.nextTick(function() {
        console.log('3');
    })
    new Promise(function(resolve) {
        console.log('4');
        resolve();
    }).then(function() {
        console.log('5')
    })
})
process.nextTick(function() {
    console.log('6');
})
new Promise(function(resolve) {
    console.log('7');
    resolve();
}).then(function() {
    console.log('8')
})

setTimeout(function() {
    console.log('9');
    process.nextTick(function() {
        console.log('10');
    })
    new Promise(function(resolve) {
        console.log('11');
        resolve();
    }).then(function() {
        console.log('12')
    })
})

2、答案

待补充

参考

1、JS事件循环机制(event loop)之宏任务/微任务