【问题标题】:Javascript & JQuery: promises executing in unexpected orderJavascript 和 JQuery:以意想不到的顺序执行的承诺
【发布时间】:2014-11-23 20:23:11
【问题描述】:

我正在尝试从两个不同的函数中获取一组对象。这些函数在数据库中执行一些查询。

我认为问题与事务的异步性质有关。

我尝试了几种替代方法来尝试使所有过程同步但没有成功。

我将详细说明生成对象的代码片段:

预期的物体形状:

[
    {
        row: 
             {
                 prit_cd_item: 7,
                 prit_st_name: "1105 - Jazzboat"
             },
        tariffs:
             [
                 {
                     cdPricing: 14,
                     dsPricing: "Operator tariff"
                 }
             ]
    }
]

函数 getTariffByProductItem:

getTariffByProductItem: function(productItemId) {
    // Return Array of tariffs
    var def = new $.Deferred();
    var tariffs = [];
    db.transaction(function(tx) {
        tx.executeSql('select pric.pric_cd_pricing, pric.pric_ds_pricing ' + 
                        'from tga_pricings pric ' +
                        'where date(\'now\') <= pric.pric_dt_valid_to ' +
                        'and date(\'now\') >= pric.pric_dt_valid_from ' +
                        'and pric.pric_cd_product_item = ?',
        [productItemId],
        function(tx,dbResult) {
            if(dbResult.rows.length) {
                for(var i = 0; i < dbResult.rows.length; i++) {
                    tariffs.push( 
                        {
                            cdPricing: dbResult.rows.item(i).pric_cd_pricing,
                            dsPricing: dbResult.rows.item(i).pric_ds_pricing
                        }
                    );
                }
                def.resolve(tariffs);   
            }
        });
    }
    , function(e) { 
        alert("There has been an error: " + e.message); 
        def.reject();
    });

    return def.promise();
}

函数editBookPaxBuyPrepare:

editBookPaxBuyPrepare: function(productId) {
var def = new $.Deferred();
var bookingId = $( '#edit-book-pax-pricing-form' ).data('bookid');
var paxId = $( '#edit-book-pax-pricing-form' ).data('paxid');
var productItems = [];

// Check for actual data
db.transaction(function(tx) {
    // Get product items for product
    tx.executeSql('select prit.prit_cd_item, prit.prit_st_name ' +
                    'from tga_products_catalog prod ' +
                    'inner join tga_product_items prit ' +
                    'on prit.prit_cd_product = prod.prod_cd_product ' +
                    'where prod.prod_cd_product = ?',
    [ productId ],
    function(tx, dbResult) {
        if(dbResult.rows.length) {
            // Set form action to EDIT
            $('#edit-book-pax-buy-form').data('formaction', 'edit');
            // Set product name label
            $('#edit-book-pax-buy-product').text(dbResult.rows.item(0).prod_ds_product);
            for(var i=0; i<dbResult.rows.length; i++) {
                // For each producItem get tariffs
                var dbRow = dbResult.rows.item(i);  
                var data = [];

                $.when(bookings.getTariffByProductItem(dbRow.prit_cd_item))
                .then(function(data) {
                    console.log("Product Item: " + dbRow.prit_st_name + " - tariffsArray: " + JSON.stringify(data));
                    productItems.push({ "row": dbRow, "tariffs": data });
                });
            }
            def.resolve(productItems);
        }   
    });

},
function(e) {
    def.reject(e);
});
return def.promise();

}

调用以上两个函数的主代码:

var listFieldset = $( '#edit-book-pax-buy-form-product-items-list' );
listFieldset.empty();
$.when(bookings.editBookPaxBuyPrepare(productId))
.done(function(productItems) {
    console.log(JSON.stringify(productItems));
    $( "#edit-book-pax-buy-product-item" ).tmpl( productItems ).appendTo( listFieldset );
    listFieldset.trigger('create');
    listFieldset.listview('refresh');
});

我得到的日志:

bookings.js:738 []
2014-11-23 20:03:06.151bookings.js:566 Product Item: 1105 - Local guide - tariffsArray: [{"cdPricing":7,"dsPricing":"Operator tariff"}]
2014-11-23 20:03:06.155bookings.js:566 Product Item: 1105 - Local guide - tariffsArray: [{"cdPricing":14,"dsPricing":"Operator tariff"}]
2014-11-23 20:03:06.159bookings.js:566 Product Item: 1105 - Local guide - tariffsArray: [{"cdPricing":15,"dsPricing":"Operator tariff"}]
2014-11-23 20:03:06.163bookings.js:566 Product Item: 1105 - Local guide - tariffsArray: [{"cdPricing":16,"dsPricing":"Operator tariff"}]

如您所见,“console.log(JSON.stringify(productItems));”在 editBookPaxBuyPrepare 函数内的循环中的 console.log 行之前执行。预期的行为是相反的:等到 editBookPaxBuyPrepare 完成,然后在 promise 中记录 returndes 数组的内容。

我的期望是:

  • 调用editBookPaxBuyPrepare,获取产品项目(每行一个)。
  • 对于每一行(产品项),在每次 for 循环迭代中调用 getTariffByProductItem 获取关税数组。
  • 对象创建正确后,返回主程序。

我需要一双好眼睛来帮我解决这个问题。

欢迎任何帮助!

谢谢。

【问题讨论】:

  • 这个问题是否与Javascript Promises not executing correctly.Two objects in JQuery tmpl using {{each …}}. 重复?这些问题之间的区别并不明显。
  • 我理解您的评论。它不是真正的重复,但它是相关的。当我发布另一个问题时,我认为它与 jQuery-tmpl 有关。由于我没有收到任何反馈,我用新方法重写了它。我知道不应该这样做。
  • 这不会造成问题,但值得了解。你可以做bookings.editBookPaxBuyPrepare(productId).done(...)。你不需要$.when() 围绕它。 $.when() 仅在您有多个承诺并且希望在它们全部完成时收到通知时才需要。否则,直接在promise上使用.then()或.done()即可。

标签: javascript jquery mysql promise javascript-objects


【解决方案1】:

你的问题是这部分代码:

for(var i=0; i<dbResult.rows.length; i++) {
  // For each producItem get tariffs
  var dbRow = dbResult.rows.item(i);  
  var data = [];

  $.when(bookings.getTariffByProductItem(dbRow.prit_cd_item))
  .then(function(data) {
      console.log("Product Item: " + dbRow.prit_st_name + " - tariffsArray: " + JSON.stringify(data));
      productItems.push({ "row": dbRow, "tariffs": data });
  });
}
def.resolve(productItems);

你在循环之后直接调用def.resolve(productItems);,但在循环内部你有$.when(bookings.getTariffByProductItem(dbRow.prit_cd_item)),它是异步的,不会阻塞循环,因此将在你调用def.resolve(productItems);后执行

另一个问题是dbRow 对于所有.then() 回调都是相同的,因为它们是在循环完成后执行的。

如果您打算在整个代码中以复杂 方式(包括循环)使用 Promises,那么我建议使用 complete 承诺库而不是 jQuery。

【讨论】:

  • 感谢您的回答。关于任何图书馆的任何建议?我正在使用 Cordova 开发一个 jQuery Mobile 应用程序。我正在调查 Q 或何时。
  • @JoséLuisGallego 我从when 开始,但目前已将我所有的项目迁移到使用bluebird。个人认为是更好的选择。另外一点是,bluebird 在其文档中使用Promise. 作为前缀,就像您在当前浏览器中本地使用它时所做的那样,另一方面,when 在文档中使用when. 作为前缀。虽然您可以自己选择 前缀,但在我看来,使用供应商名称作为文档中标准的前缀是一个糟糕的选择。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多