全部移動從.exec()
回調到.then
的代碼,並返回一個新的承諾,就當所有的其他承諾完成解析。
Product.find({'prodType': req.params.type}).lean().exec()
.then(function (product) {
var promises = [];
for (var i = 0; i < product.length; i++) {
(function(u) {
promises.push(Option.find({'prodId': product[i].productId}).lean().sort({price: -1}).limit(1).exec(function (err, highest) {
product[u].price = highest;
// not updated in returned object
}));
})(i);
}
return Promise.all(promises).then(function() {
// we want to pass the original product array to the next .then
return product;
});
}).then(function (product) {
res.send(product);
}).catch(function (err) { // the power of promise error catching!
// If any error occurs in any of the db requests or in the code, this will be called.
res.status(400);
});
而且,因爲你正在處理一個數組,.MAP使得這個更容易,消除了內IIFE的需要。
Product.find({'prodType': req.params.type}).lean().exec()
.then(function (product) {
var promises = product.map(function (p) {
return Option.find({'prodId': p.productId}).lean().sort({price: -1}).limit(1).exec(function (err, highest) {
p.price = highest;
}));
});
return Promise.all(promises).then(function() {
// we want to pass the original product array to the next .then
return product;
});
}).then(function (product) {
res.send(product);
}).catch(function (err) { // the power of promise error catching!
// If any error occurs in any of the db requests or in the code, this will be called.
res.status(400);
});