谷歌距离不适用于异步等待



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

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不返回 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'
})
};

最新更新