Event Loop

时间:2021-08-03
本文章向大家介绍Event Loop,主要包括Event Loop使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

拿自己写的例子来说明执行顺序


console.log('st');

setTimeout(()=>{
  console.log('ed');
}, 0);

let b=async()=>{
  console.log('b-st');
  return 'b-ed'
}

let a=async ()=>{
  console.log('a-st');
  
  return 'a-ed'

}


a()
.then(res=>{
  console.log(res);
})
.then(res=>{
  console.log('d');
})
.then(res=>{
  console.log('f');
})

b()
.then(res=>{
  console.log(res);
})
.then(res=>{
  console.log('e');
})
.then(res=>{
  console.log('g');
})


console.log('c');

//顺序: st, a-st, b-st, c, a-ed, b-ed, d, e, f, g, ed

任务顺序(#a.b表示#宏任务.微任务)

#1.0

  • console.log('st')'st'
  • setTimeout → 将console.log('ed')推送到#2.0
  • a()'a-st' → 将后面的.then推送到#1.1
  • b()'b-st' → 将后面的.then推送到#1.1
  • console.log('c')

#1.1

  • .then'a-ed' → 将后面的.then推送到#1.2
  • .then'b-ed' → 将后面的.then推送到#1.2

#1.2

  • .then'd' → 将后面的.then推送到#1.3
  • .then'e' → 将后面的.then推送到#1.3

#1.3

  • .then'f'
  • .then'g'

#2.0
console.log('ed')'ed'

如果引入一句await

let w=async()=>{
  console.log('w-st');
  return 'w-ed'
}

let b=async()=>{
  console.log('b-st');
  console.log(await w()); //新增的
  return 'b-ed'
}

后果就是

  • await后的w()会先执行,
  • 而b()后续代码推送到#1.1这一步(原本是第一个then推送到#1.1)
  • 第一个then被推到了#1.2(原本是第二个then推到#1.2)
    所以整体都比原本慢了一拍
    最终输出就是:st, a-st, b-st, w-st, c, a-ed, w-ed, d, b-ed, f, e, g, ed

原文地址:https://www.cnblogs.com/exkaede/p/15094425.html