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

【学习笔记】for、forEach会不会被await阻塞

思考

如果在循环遍历里加await,执行语句会等待吗?

分析

常用循环是for和forEach
分别尝试

for

/** 打印函数 **/
function printFn(str,t=100) {
    return new Promise((resolve) => {
        setTimeout(() => {
            console.log('this is setTimeout, time is '+t+'ms, and str is '+str);
            resolve(true);  // 打印完后返回 true
        }, t);
    });
}

/** 使用 async 函数来调用打印函数 **/
const main = async()=> {
  for(let i=1;i<4;i++){ // for
    console.log('for'+i)
    const res = await printFn('for'+i, (4-i)*1000) // 延迟时间是逆序,分别是3000,2000,1000
    console.log(res)
  }
}

// 调用主函数
console.log('--main--')
main();

结果很明显,for循环等待await执行完成才会继续

--main--
for1 # 全部顺序
Promise {<pending>} # main() 可忽略
this is setTimeout, time is 3000ms, and str is for1
true
for2
this is setTimeout, time is 2000ms, and str is for2
true
for3
this is setTimeout, time is 1000ms, and str is for3

await

/** 打印函数 **/
function printFn(str,t=100) {
    return new Promise((resolve) => {
        setTimeout(() => {
            console.log('this is setTimeout, time is '+t+'ms, and str is '+str);
            resolve(true);  // 打印完后返回 true
        }, t);
    });
}

/** 使用 async 函数来调用打印函数 **/
const main = async()=> {
  [1,2,3].forEach(async i=>{
    console.log('each'+i)
    const res = await printFn('each'+i, (4-i)*1000); // 延迟时间是逆序,分别是3000,2000,1000
    console.log(res);
  })
}

// 调用主函数
console.log('--main--')
main();

结果很明显,forEach不会等待await

--main--
each1 # 此处顺序,1,2,3
each2
each3
Promise {<pending>} # main() 可忽略
this is setTimeout, time is 1000ms, and str is each3 # 此处是逆序,3,2,1
true
this is setTimeout, time is 2000ms, and str is each2
true
this is setTimeout, time is 3000ms, and str is each1
true

前面顺序输出,后面输出也是按照time顺序,说明forEach(exeFn)中的多个exeFn是异步的。

总结

for循环会等待await返回,[].forEach()不会。

/** 打印函数 **/
function printFn(str,t=100) {
    return new Promise((resolve) => {
        setTimeout(() => {
            console.log('this is setTimeout, time is '+t+'ms, and str is '+str);
            resolve(true);  // 打印完后返回 true
        }, t);
    });
}

/** 使用 async 函数来调用打印函数 **/
const main = async()=> {
  // for循环会被阻塞 
  for(let i=3;i>0;i--){
    console.log('for'+i)
    const res = await printFn('for'+i, i*1000)
    console.log(res) // 等待await返回,才会继续执行,进入下一个for
  }
  // forEach不会阻塞
  [1,2,3].forEach(async i=>{
    console.log('each'+i)
    const res = await printFn('each'+i, i*1000);
    console.log(res); // 不会等待await返回,直接进入下一个
  })
}

// 调用主函数
console.log('--main--')
main();

相关文章:

  • 【2024~2025年备受关注的AI大模型】
  • 杂记:STM32 调试信息打印实现方式
  • 关于 IoT DC3 中驱动(Driver)的理解
  • SolidWorks C# How
  • go语言获取机器的进程和进程运行参数 获取当前进程的jmx端口 go调用/jstat获取当前Java进程gc情况
  • 【前端】几种常见的跨域解决方案代理的概念
  • SQLMesh系列教程-2:SQLMesh入门项目实战(上篇)
  • SQL布尔盲注、时间盲注
  • [SQL Server]从数据类型 varchar 转换为 numeric 时出错
  • 排序--四种算法
  • STM32、GD32驱动TM1640原理图、源码分享
  • HCIA项目实践--RIP相关原理知识面试问题总结回答
  • 服务器,交换机和路由器的一些笔记
  • 机器学习(李宏毅)——self-Attention
  • 常见的排序算法:插入排序、选择排序、冒泡排序、快速排序
  • 利用Java爬虫按图搜索1688商品(拍立淘):实战案例指南
  • 集成学习(一):从理论到实战(附代码)
  • sqli-lab靶场学习(六)——Less18-22(User-Agent、Referer、Cookie注入)
  • 网络工程师 (35)以太网通道
  • iptables网络安全服务详细使用
  • 梅花奖在上海|朱洁静:穿越了人生暴风雨,舞台是最好良药
  • 经济日报刊文:品牌经营不能让情怀唱“独角戏”
  • 川大全职引进考古学家宫本一夫,他曾任日本九州大学副校长
  • 前瞻|中俄元首今年将首次面对面会晤,专家:国际变局中构建更坚韧的合作架构
  • 五一假期,长三角铁路张家港、台州等多个车站客发量创新高
  • 预告:央行等部门将发声,介绍“一揽子金融政策支持稳市场稳预期”有关情况