我遇到的问题是,至少有一个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()在第二个最后一个完成之前运行。
这似乎是我身边的一种误解。有人可以告诉我我的逻辑有什么问题吗?
答案 0 :(得分:1)
你必须在每个回调中返回一些东西(promise或just object,array,...):
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);
});