【发布时间】:2016-12-04 18:27:54
【问题描述】:
我正在做一个购物车,我必须获得产品的价格才能乘以数量,但我遇到了异步问题,我无法在循环的每次迭代中获得价格。
router.get('/cartlist', function(req, res) {
var db = req.db;
var collection = db.get('cart');
collection.find({},{},function(e,docs){
var totalPrice = 0;
for(var i in docs)
{
var name = docs[i].productname;
var amount = docs[i].amount;
var products = db.get('products');
var idPrice = 0;
getPrice(products, name, function(data)
{
idPrice = data;
});
console.log(idPrice);
}
totalPrice += idPrice * amount;
console.log(totalPrice);
res.render('cartlist', {
"cartlist" : docs
});
});
});
还有回调:
function getPrice(collection, name, callback)
{
collection.findOne({"productname" : name}, {_id:0, price:1}, function(err, objs)
{
if(objs != null)
{
callback(objs.price);
}
});
}
当我显示 totalPrice 的值为 0 时。我该怎么做?我需要获取价格才能在循环中执行 totalprice += amount * price。谢谢。
【问题讨论】:
-
您能否编辑您的问题以显示来自
cart和products集合的一些示例文档?
标签: javascript node.js mongodb callback