我正在使用 NodeJS 和 MongoDB (Mongoose) 開發電子商務 Web 應用程式。
我有一個將在購物車中顯示產品的 get 路線,我很掙扎,因為在繼續執行其余代碼之前我需要完成一個功能。
該函式將專案推送到一個陣列,然后我嘗試渲染一個傳遞該陣列的視圖,但該陣列消失了。
這是我的代碼。
router.get('/cart', function (req, res) {
User.findOne({ username: req.user.username }, function (err, doc) {
// This is the array that needs to be passed
const prodAndQty = [];
const prodEntries = Object.entries(doc.shoppingCart);
// This is the function that I need to complete before continuing
prodEntries.forEach(function (entry) {
Product.findOne({ id: entry[0] }, function (err, doc) {
prodAndQty.push([doc, entry[1]]);
});
});
if (err) { console.log(err); }
else {
// If I log here, the array is empty.
console.log(prodAndQty);
if (doc) {
res.render('cart', { doc: doc, qty: prodEntries.length, products: prodAndQty });
} else {
res.render('cart', { doc: null, qty: 0, products: null });
}
}
});
});
如果我在渲染之前記錄陣列,則陣列為空。
此外,在終端中,甚至在 Mongoose 查詢執行之前就記錄了該陣列。
終端日志
如果我在正在推送的函式中記錄陣列,則陣列已正確填充,但為時已晚,無法使用。
任何幫助將不勝感激。
uj5u.com熱心網友回復:
您需要promise-based behavior為您的代碼呼叫一些東西。請參考:
- 異步函式
- 承諾
uj5u.com熱心網友回復:
嘗試這樣的事情 -
router.get('/cart', async function (req, res) {
try {
const doc = await User.findOne({ username: req.user.username });
if(!doc) {
res.render('cart', { doc: null, qty: 0, products: null });
}
const prodEntries = Object.entries(doc.shoppingCart);
// Instead of one by one searching, I used `in` operator (you can do one by one too, if you want)
const entires = prodEntries.map((prod) => {
return prod[0];
})
const prodAndQty = await Product.find({ id : { $in : entires }});
// TODO - Modify this prodAndQty array as you want
res.render('cart', { doc: doc, qty: prodEntries.length, products: prodAndQty });
} catch(err) {
throw new Error(err);
}
}
在您的方法中,發生的情況是,您正在使用回呼函式,該函式不會等待代碼在 forEach 內部執行,它只是繼續并回傳回應。
Async-await是一種語法糖,它允許您以某種方式撰寫代碼,因此它似乎是以串行方式執行的。另一種方法是使用promises。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/352349.html
標籤:javascript 节点.js 数组 MongoDB 猫鼬
上一篇:如何在運行時向下拉串列添加條目?
