数组被重新初始化无缘无故?



请看下面的代码:最后一行显示了[]为什么??

const arrcodces =[1,2,3,4]
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)
arrOfPWs_2.push({code:element.code,password:newPW})
}
function doIt() {
arrOfPWs.forEach(el =>
loopy(el)
)
}
doIt()
//********************************* */ 
console.log(arrOfPWs_2)//SHOWS [] !!!

我试过了,在console.log()的底部显示[]!!.......................................................................

  1. 调用async函数loop而不使用await
  2. doIt应该也是异步的
  3. forEach方法是同步的。console.log(arrOfPWs_2)不等待doIt结果。https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function
async function doIt() {
for(const el of arrOfPWs){
await loopy(el);
}  
)
...
await doIt();

最新更新