I have an Object, InsertDB, that contains multiple functions. I would like to execute one after the other.

Only execute function 2 InsertDB.addNot(); when function 1 InsertDB.addBk(); has completely finished looping, inserting records, and so on.

// 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();

有帮助吗?

解决方案 2

As Tommi suggeted, I had to ensure that the function returns promises then I can fire an event when all iterations are finished, I did do as follow :

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
    });

  }
}

其他提示

You should implement the functions so that they return promises, and then you can subscribe to those promises. You can use jQuery or q.js for that.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top