当前位置: 首页 > article >正文

【错题本】js事件循环机制下,记录一个意外错误

js的事件循环机制是前端的基础概念。下面我们先看两段代码:

setTimeout(()=>{
    console.log("children2")
    Promise.resolve().then(()=>{
        console.log("children3")
    })
},0)
new Promise(function(resolve,reject){
    console.log("children4")
    setTimeout(function(){
        console.log("children5")
        resolve("children6")
    },0)
}).then(res=>{
    console.log("children7")
    setTimeout(function(){
        console.log(res)
    },0)
})
console.log("start")

上面的代码输出:children4、start、children2、children3、children5、children7、children6

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

async function async2() {
  console.log("async2");
}

console.log("script start");

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

async1();

new Promise(function (resolve) {
  console.log("promise1");
  resolve();
}).then(function () {
  console.log("promise2");
});

console.log("script end");

上面的代码输出:script start、async1 start、async2、promise1、script end、async1 end、promise2、setTimeout
第二道题时,我出现一个疑惑,当await 后面跟的不是一个 Promise 对象(而是一个同步值或已经解决的 Promise),那么await 后面的代码会被放入微任务队列吗?
验证代码:

async function example() {
    console.log('Start');
    await Promise.resolve(); // 立即解决的 Promise
    console.log('After await');
}

console.log('Before async call');
example();
console.log('After async call start');

// 输出顺序:
// Before async call
// After async call start
// Start
// After await

上面的代码表明:如果 await 后面跟的不是一个异步操作,虽然await 不会真正“等待”任何东西,但它仍然会将后续代码放入微任务队列中。

结论:无论 await 后面跟的是否是一个真正需要等待的异步操作,它都会导致后续代码被放入微任务队列中执行。


http://www.kler.cn/a/541566.html

相关文章:

  • Linux ftrace 内核跟踪入门
  • 深度学习之神经网络框架搭建及模型优化
  • 第四十八章:黄山之行:与小一的奇妙冒险
  • 使用Redis实现业务信息缓存(缓存详解,缓存更新策略,缓存三大问题)
  • 【C语言标准库函数】标准输入输出函数详解[4]:二进制文件读写函数
  • ECG分析0210
  • Ada语言的区块链
  • 地平线 3D 目标检测 Bevformer 参考算法-V2.0
  • 怎么查看电脑显存大小(查看电脑配置)
  • OpenGL学习笔记(十二):初级光照:投光物/多光源(平行光、点光源、聚光)
  • JEECGBOOT前端VUE3版本浏览器兼容支持chrome>=76版本方法
  • 虚拟机+Docker配置主机代理和常见配置
  • 如何在 Java 应用中实现数据库的主从复制(读写分离)?请简要描述架构和关键代码实现?
  • Docker 和 Containerd 目录结构及存储机制
  • 基于Springboot和vue的流浪猫狗救助救援系统设计与实现(源码+数据库+文档)
  • kafka消费端之分区分配策略
  • MATLAB中extract 函数用法
  • Ubuntu 如何安装Snipaste切图软件
  • redis高级数据结构HyperLogLog
  • TCP/IP 协议图解 | TCP 协议详解 | IP 协议详解
  • 香橙派AI Pro算子开发(二)kernel直调Add算子
  • git如何把多个commit合成一个
  • Machine Learning:Introduction
  • 【Ubuntu VScode Remote SSH 问题解决】Resolver error: Error: XHR failed
  • 如何使用 DataX 连接 Easysearch
  • 鸿蒙NEXT开发-鸿蒙三方库