宏任务与微任务, event loop

event loop,先执行主线程,主线程执行完,再执行微任务,再执行宏任务,然后重复下去,这个例子有点复杂,可看分析:

分析链接

解释:微任务是在当前主线程中碰到的微任务加入,然后去执行。
setTimeout(_ => console.log(10));

new Promise(resolve => {
    resolve();
    console.log(1);
}).then(_ => {
    console.log(3);
    Promise.resolve().then(_ => {
        console.log(4);
    }).then(_ => {
        console.log(6);
        Promise.resolve().then(_ => {
            console.log(7);
        }).then(_=> {
            console.log(9);
        });
    }).then(_ => {
        console.log(8);
    });
}).then(_=> {
    console.log(5);
});

console.log(2);

进阶版:

解释:微任务是在当前主线程中碰到的微任务加入,然后去执行。
new Promise(resolve => {
    resolve()
})
    .then(() => {
        new Promise(resolve => {
            resolve()
        })
            .then(() => {
                console.log(1)
            })
            .then(() => {
                console.log(2)
            })
            .then(() => {
                console.log(3.1)
            })
    })
    .then(() => {
        console.log(1.1)
        new Promise((resolve => {
            resolve()
        }))
            .then(() => {
                new Promise(resolve => {
                    resolve()
                })
                    .then(() => {
                        console.log(4)
                    })
                    .then(() => {
                        console.log(6)
                    })
            })
            .then(() => {
                console.log(5)
            })
    })
    .then(() => {
        console.log(3)
    })
console.log(0)

进阶版2:

解释:加入return之后,promise需要递归获取最终的非promise的值,简单说就是要执行到最后一个resolve,具体原因牵扯到promise的实现

new Promise(resolve => resolve())
  .then(() => {
    return new Promise(resolve => resolve())
      .then(() => console.log(1))
      .then(() => console.log(2))
      .then(() => console.log(3.1));
  })
  .then(() => {
    console.log(1.1);
    return new Promise((resolve => resolve()))
      .then(() => {
        return new Promise((resolve) => resolve())
          .then(() => console.log(4))
          .then(() => console.log(6))
      }).then(() => console.log(5))
  }).then(() => console.log(3))

console.log(0)
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。