Sunday, 15 August 2010

sails.js - SAILS 0.10: Async & Promise issue when save to database -



sails.js - SAILS 0.10: Async & Promise issue when save to database -

it seems have issue async on promise. have tested sails-mysql, sails-mongo, sails-postgres version 0.10-rc-xx , problem happen. when utilize sails-disk, there's no problem. comment below

var storeinvoicedetail = function( detail ) { homecoming 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 value of 'results.getstockdifference' 5 product.stock += results.getstockdifference; product.save(); // when log, output is: 5, value not updated database // seems 'product.save()' @ above not called // maybe code have issues 'async' & 'promise' // know how right 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 ' + results.updateproductstock); callback(); }); }, function (err) { // no action }); }

.save() asynchronous method. rewrite updateproductstock function as:

var updateproductstock = ['getpreviousdetail', 'getstockdifference', function( cb, results ) { product .findone(results.getpreviousdetail.product) .then(function(product) { product.stock += results.getstockdifference; // note callback argument .save() product.save(function(err, product) { console.log(product.stock); cb(err, product.stock); }); }); }];

and should okay.

promise sails.js waterline async.js sails-mongo

No comments:

Post a Comment