Google 距离不适用于异步等待

Google Distance does not work with async await

我正在尝试使用 google-distance 节点包来计算两个城市之间的距离,一旦这个距离存储在 mongodb 数据库中,就在表单的其他字段旁边。我发现的问题是我不知道如何 return 将函数的值存储在数据库中,并且它总是 return 未定义。有人知道我会在哪里失败吗?

removalsCtrl.createRemoval = async (req, res) => {
    const { name, email, origin, destination } = req.body;

    let kilometers = await distance.get({ origin, destination }, function (err, data) {
        if (err) return console.log(err);
        return data.distanceValue;

    })

    const newRemoval = await new Removal({
        name,
        email,
        origin,
        destination,
        kilometers
    })

    await newRemoval.save();
    res.json({ message: 'Removal Saved' })
};

distance.get 不是 return Promise,因此您需要将它包装在一个函数中,或者将其余代码移到回调中,即

removalsCtrl.createRemoval = async (req, res) => {
  const {
    name,
    email,
    origin,
    destination
  } = req.body;

  const getKilometers = (origin, destination) => {
    return new Promise((resolve, reject) => {
      distance.get({ origin, destination }, function(err, data) {
        return err ? reject(err) : resolve(data);
      })
    })
  }

  // Be sure to handle failures with this, or however you decide to do it
  const kilometers = await getKilometers(origin, destination);

  const newRemoval = await new Removal({
    name,
    email,
    origin,
    destination,
    kilometers
  })

  await newRemoval.save();
  res.json({
    message: 'Removal Saved'
  })
};