xgqfrms™, xgqfrms® : xgqfrms's offical website of cnblogs! xgqfrms™, xgqfrms® : xgqfrms's offical website of GitHub!

js 深入原理讲解系列-事件循环 All In One

js 深入原理讲解系列-事件循环 All In One

能看懂这一题你就掌握了 js 事件循环的核心原理

不要专业的术语,说人话,讲明白!

Q: 输出下面 console.log 的正确的顺序?

console.log('Hello World!'); // 

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

async function async2() {
  console.log('async2 start');// 
  return new Promise((resolve, reject) => {
    resolve();
    console.log('async2 promise');//
  })
}

console.log('script start');// 

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

async1();

new Promise(function(resolve) {
  console.log('promise1');// 
  resolve();
}).then(function() {
  console.log('promise2');// 
}).then(function() {
  console.log('promise3');// 
});

console.log('script end');// 

A:


console.log('Hello World!', 1); // 1

async function async1() {
  console.log('async1 start', 3);// 3
  await async2();
  console.log('async1 end', 10);// 10
}

async function async2() {
  console.log('async2 start', 4);// 4
  return new Promise((resolve, reject) => {
    resolve();
    console.log('async2 promise', 5);// 5
  })
}

console.log('script start', 2);// 2

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

async1();

new Promise(function(resolve) {
  console.log('promise1', 6);//6
  resolve();
}).then(function() {
  console.log('promise2', 8);// 8
}).then(function() {
  console.log('promise3', 9);// 9
});

console.log('script end',  7);// 7



/*

Hello World! 1
script start 2
async1 start 3
async2 start 4
async2 promise 5
promise1 6
script end 7
promise2 8
promise3 9
async1 end 10
setTimeout 11

*/


翻译后的等价代码



讲解:

  1. 同步任务,先执行
  2. 遇到异步任务,先执行异步任务里面的同步任务,然后将异步任务加入到 promise 消息队列排队
  3. 当同步完成后,将promise 消息队列排队的异步任务按照 先入先出的 queue 顺序,依次取出执行
  4. promise 构造函数,在初始化的时候会立即执行

事件循环

同步任务:
异步任务: 微任务, 宏任务

Promise
thenable
IIFE
closure

constructor function

refs



©xgqfrms 2012-2020

www.cnblogs.com/xgqfrms 发布文章使用:只允许注册用户才可以访问!

原创文章,版权所有©️xgqfrms, 禁止转载 🈲️,侵权必究⚠️!


posted @ 2020-11-23 20:31  xgqfrms  阅读(113)  评论(2编辑  收藏  举报