0

Here is my code...

var schedule =new Schedule(
            {
                flightNumber: req.body.flightNumber,
                status: req.body.status,
                pickDateTime: req.body.pickDateTime,
            });

            if(req.body.passenger.length > 0){

                await req.body.passenger.forEach(async function (data) {
                    var driver
                    await Driver.findOneAndUpdate({area:data.location_code,$expr: { $gt:["$vehicle_capacity", "$capacity_occupied"]}},{ $inc: { capacity_occupied: +1 } }).then((drivers) => {
                        driver = drivers._id
                    });                 
                    await schedule.passenger.push({
                        driver: driver,
                        dropLocation: req.body.dropLocation,
                        droplong: req.body.droplong,
                        picklong: data.long
                    })
                });
            }
            console.log(schedule.passenger);

When I'm trying to access schedule.passenger inside the async function It's working but when trying to access outside the async function it's not working.

Jawad Ali
  • 3
  • 4
  • 2
    Duplicate [Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference](https://stackoverflow.com/questions/23667086/why-is-my-variable-unaltered-after-i-modify-it-inside-of-a-function-asynchron) –  Jul 26 '21 at 10:29
  • Well, it is related to asynchronicity, I am unable to understand why are you using await in an array function. I am curious. –  Jul 26 '21 at 10:58

1 Answers1

0

forEach(async function will fire bunch of async functions and once array iterations are complete, the execution will move to next code block without waiting for all the async functions to complete.

This can be taken care of by using map function and returning promises and wait for all those.

let allPromises = req.body.passenger.map(async function (data) {
 //your code goes here
});

Promise.allSettled(allPromises).then(() => {
 console.log(schedule.passenger);
});

Also await schedule.passenger.push({ is not correct because Array.prototype.push() is not an async operation.

Vivek Bani
  • 3,703
  • 1
  • 9
  • 18