1

看来我对 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
  });
}
4

1 回答 1

1

.save()是一种异步方法。updateProductStock将您的函数重写为:

var updateProductStock = ['getPreviousDetail', 'getStockDifference', function( cb, results ) {
  Product
    .findOne(results.getPreviousDetail.product)
    .then(function(product) {
      product.stock += results.getStockDifference;
      // Note the callback argument to .save()
      product.save(function(err, product) {
          console.log(product.stock);
          cb(err, product.stock);
      });    
    });
}];

你应该没事。

于 2014-06-26T22:36:52.230 回答