Skip to content
Advertisement

NodeJs push in array not working within the async function

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.

Advertisement

Answer

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.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement