为何代码中arrOfPWs_2数组最终输出为空?技术求助
为什么异步哈希密码后数组输出为空?
你编写的代码中,调用doIt()后立刻执行console.log(arrOfPWs_2)输出空数组,核心原因是异步代码的执行时机问题:
loopy是异步函数,内部的bcrypt.hash是异步操作,需要等待完成才会往arrOfPWs_2里push数据arrOfPWs.forEach(el => loopy(el))只是触发了所有异步任务,但不会等待这些任务全部完成doIt()执行后,代码会直接跳到console.log,此时所有哈希操作还在后台运行,arrOfPWs_2还没被填充,所以输出空数组
修正方案
把doIt改成异步函数,使用Promise.all来等待所有异步哈希任务完成,之后再打印数组:
const arrcodes =[1,2,3,4] // 修复原代码变量名拼写错误:arrcodces → arrcodes const arrOfPWs=[] const data=[] const arrOfPWs_2=[] const base=[ '2','3','4','5','6','7','8','9', 'a','b','c','d','e','f','g','h','i', 'k','m','n','p','q','r','s','t','u', 'v','w','y','z','+','=','*','.','/' ] // 生成随机密码部分 for(let i=0;i<arrcodes.length;i++){ let pw='' for(let j=0;j<6;j++){ pw=pw+base[Math.floor(Math.random()*base.length)] } data.push(pw) } for(let i=0;i<arrcodes.length;i++){ arrOfPWs.push({code:arrcodes[i],password:data[i]}) } // 异步哈希函数 async function loopy(element) { const newPW = await bcrypt.hash(element.password, 3) return {code:element.code,password:newPW} // 改为返回结果,避免直接修改全局数组 } async function doIt() { // 用Promise.all等待所有异步任务完成,收集结果 const results = await Promise.all(arrOfPWs.map(el => loopy(el))) arrOfPWs_2.push(...results) } // 执行并等待完成后打印 doIt().then(() => { console.log(arrOfPWs_2) // 此时数组已填充完成 })
额外优化点
- 修复原代码中变量名拼写错误:
arrcodces→arrcodes - 让
loopy返回结果而非直接修改全局数组,代码更模块化、可维护 - 使用
Promise.all批量处理异步任务,实现并行执行哈希操作,效率更高
内容的提问来源于stack exchange,提问作者Pouria
相关产品推荐
相关产品推荐

