【问题标题】:Add results from second query to answer from first query将第二个查询的结果添加到第一个查询的答案
【发布时间】:2018-03-20 13:07:46
【问题描述】:

我的问题是,至少有一个 then() 函数没有等待前一个函数结束。

代码被缩短但大致是这样的:

        var objCheck = {};

    var id = thisClick.attr('id');
    APP.db.checkInfo.get(id).then(function (resultDetail) {
        objCheck.details = resultDetail;
    }).then(function () {
        var checkPoints = APP.db.checkRooms.where('check_id').equals(id);
        checkPoints.toArray(function(dataArray) {
            dataArray.measures = [];
            objCheck.checkpoints = dataArray;
        });
    }).then(function () {
        var arrayLength = objCheck.checkpoints.length;

        for (var i = 0; i < arrayLength; i++) {
            var roomId = objCheck.checkpoints[i].room_id;
           var measure = APP.db.measures.where('room_id').equals(roomId);
           measure.toArray(function(dataArray) {
            objCheck.checkpoints[i].measures = dataArray;
        });
        }
    }).then(function () {
        $.ajax(
         // Here I send then objCheck to the server
       ).done(...);
    }).catch(function(error) {
     alert ("Error upload: " + error);
    });

如果我在最后将 objCheck 打印到控制台,我会看到测量值已填写。但在 ajax() 调用中,它不会一起发送。所以在我看来,最后一个 then() 在倒数第二个完成之前运行。

这似乎是我的误解。谁能告诉我我的逻辑有什么问题?

【问题讨论】:

标签: javascript dexie


【解决方案1】:

你必须在每个 then 的回调中返回一些东西(promise 或只是对象、数组、...):

var objCheck = {};

var id = thisClick.attr('id');

APP.db.checkInfo.get(id).then(function (resultDetail) {
    objCheck.details = resultDetail;
    return objCheck;
}).then(function () {
    var checkPoints = APP.db.checkRooms.where('check_id').equals(id);
    return checkPoints.toArray();
}).then(function (dataArray) {
    dataArray.measures = [];
    objCheck.checkpoints = dataArray;
    var arrayLength = objCheck.checkpoints.length;

    var promises = objCheck.checkpoints.map(function(chk) {
        var roomId = chk.room_id;
        return APP.db.measures.where('room_id').equals(roomId);
    });

    return Promise.all(promises);
}).then(function(res) {
    objCheck.checkpoints.forEach(function(chekpoint, i) {
        chekpoint.measures = res[i];
    });
    return objCheck
}).then(function () {
    $.ajax(
        // Here I send then objCheck to the server
    ).done(...);
}).catch(function(error) {
    alert ("Error upload: " + error);
});

【讨论】:

  • 我现在看到我需要了解更多关于 Promises 的知识。您的代码中有一个错误。在“chekpoint.measures = res[i];”这一行中元素 res[i] 是一个 Promise 对象,而不是我需要的数据。我现在试着解决这个问题。到目前为止,谢谢。
猜你喜欢
  • 2015-03-16
  • 2022-10-07
  • 1970-01-01
  • 2013-11-01
  • 1970-01-01
  • 2021-01-11
  • 2017-02-09
  • 2017-09-10
  • 2019-05-29
相关资源
最近更新 更多