我具有以下涉及猫鼬的功能:
let username = userObject.username;
Purchase.find({
account: username,
fufilled: true
})
.populate("keys")
.exec(function(err, foundPurchases) {
if (err) {
return inStockItems;
} else {
if (foundPurchases.length === 0) {
return inStockItems;
} else {
// these lists will be a list of IDs of game detail entries in the database
let listOfReceivedIds = foundPurchases.keys.map(obj => obj.game);
for (let i = 0; i < inStockItems.length; i++) {
if (inStockItems.length <= minimum) {
return inStockItems;
}
let currentProductAnalysing = inStockItems[i];
if (listOfReceivedIds.includes(currentProductAnalysing._id)) {
console.log("removing product");
inStockItems.splice(i, 1);
}
}
return inStockItems;
}
}
});
我正在运行以下函数,该函数返回undefined
inStockItems = function_name(inStockItems, userObject, amount);
如何重写函数,以便函数返回inStockItems
而不是undefined
的值。谢谢。
答案 0 :(得分:0)
.exec
会返回查询结果的承诺。这里的函数需要调用.exec()
并更改其返回值,以返回与该函数不同的东西:
async function function_name(inStockItems, userObject, amount) {
const foundPurchases = await Purchase.find({
account: username,
fufilled: true
})
.populate("keys")
.exec();
if (foundPurchases.length === 0) {
return inStockItems;
} else {
let listOfReceivedIds = foundPurchases.keys.map(obj => obj.game);
for (let i = 0; i < inStockItems.length; i++) {
if (inStockItems.length <= minimum) {
return inStockItems;
}
let currentProductAnalysing = inStockItems[i];
if (listOfReceivedIds.includes(currentProductAnalysing._id)) {
console.log("removing product");
inStockItems.splice(i, 1);
}
}
return inStockItems;
}
}
另一种选择是将回调参数传递给函数,然后从exec()
回调中调用它,但诺言通常更干净。