如何等待IndexedDB中的AJAX响应完成。我有波纹管代码,如果我运行它async,第二个事务将所有响应链接到第一个响应中的最后一个项目。我会在登录时从服务器填充报告和收据的存储,以便我可以在需要时离线工作。如果我使它同步,它可以正常工作但是从用户体验方面来看很糟糕,因为应用程序冻结了一点,所以我想避免这种情况。有没有人有建议?
var DBRequest = window.indexedDB.open(IDBName, IDBVersion);
DBRequest.onerror = function(event) {
console.log("error: ");
};
DBRequest.onsuccess = function(event) {
var response = DBRequest.result;
SExpenses.removeAll();
var z=0;
Ext.Ajax.request({
url:App.url.expenses,
method: 'GET',
async:true,
params: {
user_guid: App.user.guid,
limit: 25
},
success: function(res){
var result = Ext.decode(res.responseText);
var dataIDB = response.transaction(["ReportDataLocal"],'readwrite').objectStore("ReportDataLocal");
dataIDB.clear();
var receiptIDB = response.transaction(["ReceiptsLocal"],'readwrite').objectStore("ReceiptsLocal");
receiptIDB.clear();
var savedID, savedRecID;
Ext.each(result.data, function(item){
z++;
SExpenses.insert(0,item);
var newObject = response.transaction(["ReportDataLocal"], "readwrite")
.objectStore("ReportDataLocal")
.add({DESCRIPTION: item.DESCRIPTION, BILLING_QTY: item.BILLING_QTY,
TRAVEL_EXPENSES: item.TRAVEL_EXPENSES,REQUEST_TYPE_ID: item.REQUEST_TYPE_ID,
SERVER_ID: item.SERVER_ID
});
newObject.onsuccess = function(event){
savedID = event.target.result;
SExpenses.findRecord('SERVER_ID',item.SERVER_ID).set({ID:savedID});
Ext.Ajax.request({
url: App.url.receipts,
async: true,
method: 'GET',
params: {
Request_Log_RC: item.SERVER_ID
},
success: function(retrieve){
var result2 = Ext.decode(retrieve.responseText);
Ext.each(result2.data,function(item2){
SReceipt.add(item2);
var newReceiptIDB = response.transaction(["ReceiptsLocal"],'readwrite')
.objectStore("ReceiptsLocal");
newReceiptIDB.add({EXPENSE_AMOUNT: item2.EXPENSE_AMOUNT, EXPENSE_CURRENCY_ID:item2.EXPENSE_CURRENCY_ID,
EXPENSE_NAME: item2.EXPENSE_NAME, REPORT_ID: savedID, CURRENCY_ABB: item2.CURRENCY_ABB,
EXPENSE_IMAGE: null, SYNCED: true, DELETED: item2.DELETED,
SERVER_ID: item2.SERVER_ID, SERVER_REPORT_ID: item.SERVER_ID,
EXPENSE_EXCHANGE_RATE: null
});
newReceiptIDB.onsuccess = function(event){
savedRecID = event.target.result;
SReceipt.findRecord('SERVER_ID',item2.SERVER_ID).set({ID:savedRecID});
};
});
}
});
};
});
}
});
};
答案 0 :(得分:1)
所以你需要做的就是绑定项目https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind
基本上,如果您在多个项目上执行异步调用,并且需要回调来保留原始调用的索引,则绑定索引并将其传入。
var controller = ['$scope','$injector', function($scope, $injector){
$scope.dependencies = [];
$scope.injectFromString = function(dependency){
$scope.dependencies.push($injector.get(dependency));
};
}];`
这将使i保持在回调范围内。
从您的代码看起来您希望项目保留在上下文中,因此如果您将绑定添加到此
var returnData = [];
var a = 10;
for(var i = 0; i < a.length; i++) {
someAysncCall(function(data){
returnData[i] = data;
}).bind(null, i);
}
应该有效