function vegetables(list){
if(list){
this.list = list;
const vegetableIDs = _.pluck(list,'_id');
Product.find({'_id':{$in:vegetableIDs}}).then((resultVegetables)=>{
list.forEach(vegetable=>{
let num = list.indexOf(vegetable);
vegetable._id = resultVegetables[num];
vegetable.pricePerItem = (vegetable._id.unitPrice * vegetable.quantity)/100;
});
console.log(list)
}).catch(err=> console.log(err))
}
}
在此功能中,当我console.log(list)时,它可以正常工作并返回预期的结果。但是我想在其他地方使用它,并将函数的返回值存储到变量中。const veg = hero.vegetables(vegetables);
当我用console.log(list)
替换return list
时,我得到一个不确定的返回值。这是什么问题。
您必须将await
调用括在try catch
块中。我已对代码进行了必要的更改(希望对您有帮助)
function async vegetables(list){
if(list){
this.list = list;
const vegetableIDs = _.pluck(list,'_id');
try{
const resultVegetables=await Product.find({'_id':{$in:vegetableIDs}});
list.forEach(vegetable=>{
let num = list.indexOf(vegetable);
vegetable._id = resultVegetables[num];
vegetable.pricePerItem = (vegetable._id.unitPrice * vegetable.quantity)/100;
});
console.log(list)
}catch(err){
console.log(err);
}
}
}
而且您也无法将async/await
语法与promise
(回调)]混合使用>