event循环微任务和宏任务

微任务 promise process.nextTick
宏任务 setTimeout setInterval I/O script
同一次事件循环中 微任务永远在宏任务之前执行
一旦遇到await 就立刻让出线程,阻塞后面的代码
等候之后,对于await来说分两种情况

  • 不是promise 对象:await会阻塞后面的代码,先执行async外面的同步代码,同步代码执行完毕后,在回到async内部,把promise的东西,作为await表达式的结果
  • 是promise对象:await 也会暂停async后面的代码,先执行async外面的同步代码,等着 Promise 对象 fulfilled,然后把 resolve 的参数作为 await 表达式的运算结果。
    如果一个 Promise 被传递给一个 await 操作符,await 将等待 Promise 正常处理完成并返回其处理结果。

1、案例一

 setTimeout(function(){
     console.log('定时器开始啦')
 });
 
 new Promise(function(resolve){
     console.log('马上执行for循环啦');
     for(var i = 0; i < 10000; i++){
         i == 99 && resolve();
     }
 }).then(function(){
     console.log('执行then函数啦')
 });
 
 console.log('代码执行结束');

执行结果:


image.png

2、案例二

setTimeout(() => console.log('setTimeout1'), 0);  //1宏任务
setTimeout(() => {                              //2宏任务
    console.log('setTimeout2');
    Promise.resolve().then(() => {
        console.log('promise3');
        Promise.resolve().then(() => {
            console.log('promise4');
        })
        console.log(5)
    })
    setTimeout(() => console.log('setTimeout4'), 0);  //4宏任务
}, 0);
setTimeout(() => console.log('setTimeout3'), 0);  //3宏任务
Promise.resolve().then(() => {//1微任务
    console.log('promise1');
})

执行结果:


image.png

3、案例三

async function async1() {
    console.log( 'async1 start' )
    await async2()
    console.log( 'async1 end' )
}
async function async2() {
    console.log( 'async2' )
}
async1()
console.log( 'script start' )

执行结果
async1 start
async2
script start
async1 end

4、案例四

async function async1() {
    console.log( 'async1 start' ) //2
    await async2()
    console.log( 'async1 end' )//7
}
async function async2() {
    console.log( 'async2' )//3
}
console.log( 'script start' ) //1
setTimeout( function () {
    console.log( 'setTimeout' )//8
}, 0 )
async1();
new Promise( function ( resolve ) {
    console.log( 'promise1' )//4
    resolve();
} ).then( function () {
    console.log( 'promise2' ) //6
} )
console.log( 'script end' )//5

执行结果:


image.png

5、案例五

new Promise( ( resolve, reject ) => {
    console.log( "promise1" )
    resolve()
} )
.then( () => {
    console.log( 1 )
} )
.then( () => {
    console.log( 2 )
} )
.then( () => {
    console.log( 3 )
} )

new Promise( ( resolve, reject ) => {
    console.log( "promise2" )
    resolve()
} )
.then( () => {
    console.log( 4 )
} )
.then( () => {
    console.log( 5 )
} )
.then( () => {
    console.log( 6 )
} )

执行结果:


image.png

6、案例六

async function t1 () {
  console.log(1)
  console.log(2)
  await new Promise(resolve => {
    setTimeout(() => {
      console.log('t1p')
      resolve()
    }, 1000)
  })
  await console.log(3)
  console.log(4)
}

async function t2() {
  console.log(5)
  console.log(6)
  await Promise.resolve().then(() => console.log('t2p'))
  console.log(7)
  console.log(8)
}

t1()
t2()

console.log('end')

执行结果:


image.png

你可能感兴趣的:(event循环微任务和宏任务)