【问题标题】:NodeJs push in array not working within the async functionNodeJs 推入数组在异步函数中不起作用
【发布时间】:2021-10-02 07:10:31
【问题描述】:

这是我的代码...

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

当我尝试访问异步函数内部的 schedule.passenger 时,它正在工作,但是当我尝试访问异步函数外部时,它不起作用。

【问题讨论】:

标签: javascript node.js mongoose async-await


【解决方案1】:

forEach(async function 将触发一堆异步函数,一旦数组迭代完成,执行将移至下一个代码块,而无需等待所有异步函数完成。

这可以通过使用map 函数并返回承诺并等待所有这些来解决。

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

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

另外await schedule.passenger.push({ 也不正确,因为Array.prototype.push() 不是异步操作。

【讨论】:

  • 是不是也和变量作用域有关?
  • 哪个变量?
  • schedule.passenger,我也看不到对象中的乘客数组。
  • 因为schedule 在外部范围内,因此可以添加属性并将其可用。但是await schedule.passenger.push({ 不正确,因为Array.prototype.push() 不是异步操作。
  • @RajdeepDebnath 你是个了不起的男孩......谢谢你让我开心
猜你喜欢
  • 2019-06-03
  • 2020-12-19
  • 2017-06-15
  • 1970-01-01
  • 1970-01-01
  • 2021-09-05
  • 1970-01-01
  • 2021-07-02
  • 1970-01-01
相关资源
最近更新 更多