0

I have two functions on my backend that essentially do the following:

const function2 = async(var1, var2, var3, var4) => {
  var x = await function1(var1);
  console.log(x);
}
var function1 = async function (var1){
  var array = [];
  var1.forEach(async function(val){
    try{
      smallarr = await Item.find({
        val:val.x
      })
      array.push(smallarr);
    }
  })
  console.log(array);
  return array;
}

However, the log statement in the function2 is getting called before the log statement in function1. I'm going off of the following example from an old StackExchange thread

Example screenshot

What is going wrong in my code? What am I not understanding about async/await? I can provide the actual code instead of the cute example, but they're pretty big functions.

1 Answers1

2

The forEach call is not waiting, its callback is an async function that returns promises, but those are not awaited. Its return value is going into the void. By consequence, console.log(array); is executed before the array is populated with values.

You can fix this by using a normal for loop. NB: a try without a catch is not very useful (and would need a finally), so you could just leave that out.

for (let val of var1) {
    smallarr = await Item.find({ val:val.x })
    array.push(smallarr);
}
trincot
  • 317,000
  • 35
  • 244
  • 286
  • You can add the async keyword to the variable and it will work: myArray.forEach(async x => await DBModel.create({something: x})) – Daniel Tkach Dec 22 '21 at 23:38
  • 1
    @Daniel, you just repeat the code-pattern of the Asker, and the problem associated with it: the `forEach` call will not await the promises that are created in the callback given to it. My answer actually explains this, so I think you missed the point. – trincot Dec 23 '21 at 08:09
  • It does seem to be waiting, and it does work. I think you could give it a test. – Daniel Tkach Dec 28 '21 at 18:40
  • 1
    No, Daniel, it doesn't work reliably. That's why the Asker asked the question -- because it doesn't (always) work like that. `forEach` is synchronous. – trincot Dec 28 '21 at 18:42