async on promise に問題があるようです。Sails-mysql、sails-mongo、sails-postgres バージョン 0.10-rc-XX でテストしたところ、問題が発生しました。しかし、sails-disk を使用する場合は問題ありません。以下の私のコメントを見てください
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
});
}