0

I use sails.js to update stock data from difference variable. When I do, console.log(product.stock), the value is 4. But it seems product.save() function below is not executed because attribute stock still not changed to 4. I guess the problem is at promise. Anybody know how to fix this?

exports.updateProductStock = function (details) {

  details.forEach(function( detail ) {
    var findPrevDetailRule = {
      invoice: detail.invoice,
      product: detail.product.id
    };

    var createPrevDetailRule = {
      invoice: detail.invoice,
      product: detail.product.id,
      quantity: detail.quantity
    };

    var requirementBeforeUpdateStock = [
      PreviousDetail.findOne(findPrevDetailRule).sort('createdAt desc').then(),
      PreviousDetail.create(createPrevDetailRule).then()
    ];

    Q.all(requirementBeforeUpdateStock)
      .spread(function( prevDetail, newPrevDetail ) {
        var difference = detail.quantity - prevDetail.quantity;
        return {
          prevDetail: prevDetail,
          difference: difference
        };
      })
      .then(function( results ) {
        Product.findOne(results.prevDetail.product).then(function(product) {
          product.stock += results.difference;
          // maybe this below is not execute
          product.save();
          console.log(product.stock);
        });
      })
  });

Note: I use sails 0.10-rc8. Have tested with sails-mysql, sails-mongo, sails-postgres, but still same.

Pewh Gosh
  • 1,031
  • 1
  • 11
  • 29

1 Answers1

0

.save() accepts a callback with which you can report success/failure.

For example, you can repost back to the client (from the sails documentation) :

product.save(function (err) {
    if (err) return res.send(err, 500);
    res.json(product);
});

Depending on scope, you may need to pass res into your function

Alternatively, monitor success/failure in the console, eg ,

product.save(function (err) {
    if (err) console.log('save error: ' + err);//assuming err to be a string
    console.log('save success');
});

Should at least give you a clue as to what's going wrong.

Roamer-1888
  • 19,138
  • 5
  • 33
  • 44