【问题标题】:SailsJS how to correct this promise issue?SailsJS 如何纠正这个承诺问题?
【发布时间】:2014-06-24 03:31:08
【问题描述】:

我使用sails.js 从difference 变量更新股票数据。当我这样做时,console.log(product.stock),值是 4。但似乎下面的 product.save() 函数没有执行,因为属性 stock 仍然没有更改为 4。我想问题是有希望的。有人知道如何解决这个问题吗?

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);
        });
      })
  });

注意:我使用sails 0.10-rc8。用sails-mysql、sails-mongo、sails-postgres测试过,还是一样。

【问题讨论】:

    标签: promise sails.js waterline


    【解决方案1】:

    .save() 接受一个回调,您可以通过该回调报告成功/失败。

    例如,您可以重新发布回客户端(来自sails 文档):

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

    根据范围,您可能需要将 res 传递到您的函数中

    或者,在控制台中监控成功/失败,例如,

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

    至少应该给你一个关于出了什么问题的线索。

    【讨论】:

      猜你喜欢
      • 2011-07-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-10-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多