2014-04-24 47 views
0

我有一個Object,InsertDB,它包含多個函數。我想一個接一個地執行。執行多個功能

只有執行功能2 InsertDB.addNot();當函數1 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

使用回調(從異步調用)執行相繼。在function1的回調中執行function2,依此類推。 –

回答

0

由於托米suggeted,我必須確保該函數返回的承諾那麼當所有迭代完成後,我可以觸發一個事件,我做如下:

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

    } 
} 
1

您應該實現的功能,使他們返回的承諾,然後你可以訂閱這些承諾。你可以使用jQuery或q.js。

+0

謝謝Tommi,那就是我所做的。 – Awena