我有一个包含多个函数的对象InsertDB
。我想一个接一个地执行。
仅当功能1 InsertDB.addNot();
完成循环,插入记录等时,才执行功能2 InsertDB.addBk();
。
// Object with 7 functions to be called. Each performs a loop and insert records into IndexedDB
InsertDB = {
addBk: function(Object) {
if (Object.hasOwnProperty("Books")) {
for (var i = 0, j = Object["Books"].length; i < j; i++) {
server.Books.add({
title: Object["Books"][i].id,
content: Object["Books"][i]
});
}
}
},
addNot: function(Object) {
if (Object.hasOwnProperty("Notifications")) {
for (var i = 0, j = Object["Notifications"].length; i < j; i++) {
server.Notifications.add({
content: Object["Notifications"][i]
});
}
}
} etc...
}
//On Ajax success event, run above functions one after the other as described above.
Synchronize = {
Start: function(){
return $.ajax({
......
success: function(data){
var Object = $.parseJSON(data);
InsertDB.addBk(Object);
InsertDB.addNot(Object);
InsertDB.addUser(Object);
InsertDB.addHistory(Object); ect...
}
}};
Synchornize.Start();
答案 0 :(得分:1)
您应该实现这些功能,以便它们返回承诺,然后您可以订阅这些承诺。您可以使用jQuery或q.js。
答案 1 :(得分:0)
正如Tommi所说,我必须确保函数返回promises然后我可以在所有迭代完成时触发事件,我的确如下:
InsertDB = {
addBk: function(Object) {
if (Object.hasOwnProperty("Books")) {
var promises = [],p;
for (var i = 0, j = Object["Books"].length; i < j; i++) {
p = server.Books.add({
title: Object["Books"][i].id,
content: Object["Books"][i]
});
promises.push(p);
}
$.when.apply($, promises).done(function() {
// callback function when all iterations are finished
});
}
}