-1

I have a foreach loop, where I am creating an object. I am able to get that object inside forEach loop, but not able to get outside loop. Can anyone suggest what I am doing wrong. Here is my code:

   let errorObj
   let versionError 
   Object.keys(myObj).forEach(async function (name) {
       let dataStr = await getData(name)
       if(dataStr!==''){
         versionError.push(dataStr)
         errorObj = JSON.stringify(versionError)
       }
       console.log(errorObj) //getting object 
     })
    console.log(errorObj) //not getting object
  • 1
    `let` means the variable is scoped to within the function. You'll need to save it to a more globally scope variable to access it outside of the function. – mykaf Jul 07 '23 at 18:00
  • Here is the [documentation for let](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let). – mykaf Jul 07 '23 at 18:01
  • 4
    Even with a more global scope as suggested above, you'll still run into a problem because of the `async` `forEach`. You may want to look at https://stackoverflow.com/questions/49938266/how-to-return-values-from-async-functions-using-async-await-from-function – jnpdx Jul 07 '23 at 18:04
  • I have declared versionError and errorObj outside forEach loop – Ranjan Kumar Jul 08 '23 at 01:01
  • @jnpdx I think this would solve my problem. Thanks. – Ranjan Kumar Jul 08 '23 at 01:14

1 Answers1

0

The official documentation suggests not to use forEach with async/await. ( https://plainenglish.io/blog/async-await-foreach )

I have changed the forEach function with for, and it worked for me.

const getVersionError = async() => {
   for await (let name of Object.keys(zipData.files)){
     let dataStr = await getData(name)
     if(dataStr!==''){
       versionError.push(dataStr)
       errorObj = JSON.stringify(versionError
     }
   }
   return versionError
}
Emre Bener
  • 681
  • 3
  • 15