user164788
user164788

Reputation: 1

Async Javascript with MongoDB -

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.

Upvotes: 0

Views: 76

Answers (1)

trincot
trincot

Reputation: 350202

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);
}

Upvotes: 2

Related Questions