0

Look at this code please: at the last line, it shows [] why??

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 [] !!!

i tried and in the console.log() at the bottom it shows []!!! .......................................................................

Pouria
  • 13
  • 4
  • 1
    Does this answer your question? [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) `loopy` is an asynchronous function, but you execute `console.log` synchronously. – Heiko Theißen Dec 28 '22 at 16:42
  • check if this one work or not const newPW = await bcrypt.hash( element.password, 3) – Mahadev Mirasdar Dec 28 '22 at 17:41
  • @Heiko Theißen it looks a lot like mine. thanks – Pouria Dec 28 '22 at 18:09
  • @Mahadev Mirasdar the funny things is inside the loop itself the arrOfPWs actually gets data but when outside it gets empty. – Pouria Dec 28 '22 at 18:11

1 Answers1

0
  1. You call async function loopy without await.
  2. doIt should be async too.
  3. forEach method is synchronous. console.log(arrOfPWs_2) does not wait doIt results. 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();