0

The below JavaScript is returning a strange version of an array. The below forEach logs nothing to console. I'm probably missing something quite fundamental here, but I know for a fact that the array is populated...unless it's not populated until later due to being async and Chrome just evaluates the console.log after the fact?

let damageRollStringArr = []

monster.damage_types.forEach(async (damageTypeName) => {
    const damageType = await checkResponseAndReturnValue(await DamageTypesService.findDamageType(damageTypeName.trim()))

    if (damageType !== null) {
        damageRollStringArr.push(damageType.damage)
    }
})

damageRollStringArr.forEach(el => console.log(el))

// Was returning an empty array[] with objects inside?
return damageRollStringArr

Thanks

Hamish
  • 2,763
  • 1
  • 17
  • 21
ged12345
  • 9
  • 1

1 Answers1

0

demageRollStringArr.forEach (2nd foreach) wont wait for monster.demage_types.forEach (1st foreach) to execute although there is async await in the first forEach

To achieve what you want to do, try this,

let damageRollStringArr = []
const promises = monster.damage_types.map(async (damageTypeName) => {
    const damageType = await checkResponseAndReturnValue(await DamageTypesService.findDamageType(damageTypeName.trim()))
    if (damageType !== null) {
        damageRollStringArr.push(damageType.damage)
    }
})
await Promise.all(promises)
damageRollStringArr.forEach(el => console.log(el))
return damageRollStringArr

Or, you can use normal for() loop to replace 1st foreach

let damageRollStringArr = []
for(let i = 0; i < monster.demage_types.length; i++) {
    const damageType = await checkResponseAndReturnValue(await DamageTypesService.findDamageType(damageTypeName.trim()))
    if (damageType !== null) {
        damageRollStringArr.push(damageType.damage)
    }
}
damageRollStringArr.forEach(el => console.log(el))
return damageRollStringArr

1st solution will run the loop parallel,
2nd solution will run the loop sequential

LHJ
  • 672
  • 5
  • 13
  • Thanks for this, LHJ. I thought there was an issue with the data I was being returned from a response call, not the forEach function having an issue with async await calls. I've now done reading up this: I need to understand forEach a whole lot better than I currently do. – ged12345 Oct 19 '20 at 15:09