1
看起來我對promise有異議。我已經測試了sails-mysql,sails-mongo,sails-postgres版本0.10-rc-XX,並且問題發生了。但是當我使用sails-disk時,沒有問題。看看我的意見如下SAILS 0.10:保存到數據庫時出現Async&Promise問題
var storeInvoiceDetail = function(detail) {
return function(cb) {
cb(null, detail);
};
}
var getPreviousDetail = ['storeInvoiceDetail', function(cb, results) {
var invoiceDetail = results.storeInvoiceDetail;
PreviousDetail
.findOne({
invoice: invoiceDetail.invoice,
product: invoiceDetail.product.id
})
.sort('createdAt desc')
.exec(cb);
}];
var createPreviousDetail = ['storeInvoiceDetail', function(cb, results) {
var invoiceDetail = results.storeInvoiceDetail;
PreviousDetail
.create({
invoice: invoiceDetail.invoice,
product: invoiceDetail.product.id,
quantity: invoiceDetail.quantity
})
.exec(cb);
}];
var getStockDifference = ['storeInvoiceDetail', 'getPreviousDetail', function(cb, results) {
var difference = results.storeInvoiceDetail.quantity - results.getPreviousDetail.quantity;
cb(null, difference);
}];
// see here
var updateProductStock = ['getPreviousDetail', 'getStockDifference', function(cb, results) {
Product
.findOne(results.getPreviousDetail.product)
.then(function(product) {
// imagine the value of 'results.getStockDifference' is 5
product.stock += results.getStockDifference;
product.save();
// when I do log, the output is: 5, but this value is not updated to database
// It seems 'product.save()' at above is not called
// maybe this code have issues with 'async' & 'promise'
// anybody know how to correct this?
console.log(product.stock);
cb(null, product.stock);
});
}];
exports.updateProductStock = function (details) {
var beforeModifyProductStock = {};
async.each(details, function(detail, callback) {
beforeModifyProductStock = {
storeInvoiceDetail: storeInvoiceDetail(detail),
getPreviousDetail: getPreviousDetail,
createPreviousDetail: createPreviousDetail,
getStockDifference: getStockDifference,
updateProductStock: updateProductStock
};
async.auto(beforeModifyProductStock, function(err, results) {
console.log('now latest stock is ' + results.updateProductStock);
callback();
});
}, function (err) {
// no action
});
}
你爲什麼在這裏使用'async'?你已經在你的代碼中擁有更強大的承諾... –
@Benjamin因爲我想迭代'細節'變量並將其拋入'updateProductStock'函數。它是異步的,所以我不能使用_.each。你介意,如果你給我的例子只使用'承諾'? – user3741665