无法在函数中推送数组

时间:2018-11-09 08:23:48

标签: javascript node.js express mongoose

我知道这已经被问过了,但我似乎找不到答案,我的阵列无法推入datahasil,如何将阵列hasil推入datahasil ... ??

const data1 = await JadwalBooking.aggregate([{
    $project: {
      "keterangan": "$keterangan",
      "jumlah_tersisa": "$datalayout.jumlah_kursi_tersisa",
      "flag": "$flag",
      "date1": "$datamisa.date",
    }
  },
  {
    $match: {
      flag: 1
    },
  },

], function(err, result) {
  var datahasil = []
  result.forEach(async(item) => {
    const hasil = await DetailBookingMisa.find({
      $or: [{
          flag: 3
        },
        {
          flag: 4
        }
      ],

      $and: [{
        jadwalbookingmisa: item._id
      }]
    }, )
    datahasil.push(hasil)
  })
});

enter image description here

1 个答案:

答案 0 :(得分:0)

您为forEach函数提供了一种异步方法,该方法删除了其同步特性,因此,请使用map并在结果数组上等待Promise.all:

const data1 = await JadwalBooking.aggregate([{
    $project: {
      "keterangan": "$keterangan",
      "jumlah_tersisa": "$datalayout.jumlah_kursi_tersisa",
      "flag": "$flag",
      "date1": "$datamisa.date",
    }
  },
  {
    $match: {
      flag: 1
    },
  },

], async function(err, result) {
  const datahasil = await Promise.all(result.map(async(item) => {
    const hasil = await DetailBookingMisa.find({
      $or: [{
          flag: 3
        },
        {
          flag: 4
        }
      ],

      $and: [{
        jadwalbookingmisa: item._id
      }]
    })
    return hasil;
  });
  console.log(datahasil);
});