2012-10-03 35 views
1

我有以下代碼環與遞延對象,並承諾

$.when(tableInsert("index.php/get/sync/riesgos", insert_riesgo, evalua.webdb.db, callback)).then(function(){ 
     update_records("riesgos"); 
     $.when(tableInsert("index.php/get/sync/estancias", insert_estancia, evalua.webdb.db, callback)).then(function(){ 
      update_records("estancias"); 
      $.when(tableInsert("index.php/get/sync/riesgosestancias", insert_riesgoestancia, evalua.webdb.db, callback)).then(function(){ 
       update_records("riesgosestancias"); 
      }); 
     }); 
    }); 

我試圖找到如何將它的內部集成了環路或$。每次循環,所以它等待承諾在下一次迭代之前完成。起初,它看起來像三個調用將更容易嵌套,但這只是一段代碼,嵌套調用現在計數15!

回答

5

那麼,你需要數據的數組第一,例如:

var calls = [ 
    { 
     url: "index.php/get/sync/riesgos", 
     func: insert_riesgo, 
     update: "riesgos" 
    }, 
    ... 
]; 

,然後你可以連續使用.pipe[docs]來電:

var def = (new $.Deferred()).resolve(); 

$.each(calls, function(call) { 
    def = def.pipe(function() { 
     return tableInsert(call.url, call.func, evalua.webdb.db, callback).done(function() { 
      update_records(call.update); 
     ]); 
    }); 
}); 

沒有必要在$.when您例。通過它

webdb.tables=[{ 
    name: "riesgos", 
    callback: insert_riesgo, 
},{ 
    name: "estancias", 
    callback: insert_estancia, 
},{ 
    name: "riesgosestancias", 
    callback: insert_riesgoestancia, 
}]; 

,並使用遞歸函數循環:

0

我看到你的答案,@費利克斯 - 克林之前一直在思考,來到一個類似的方法:

製造陣列

var i=0; 
    function recursive(){ 
     $.when(tableInsert("index.php/get/sync/"+webdb.tables[i].name, webdb.tables[i].callback, webdb.db, callback)).then(function(){ 
      update_records(webdb.tables[i].name); 
      if(++i<webdb.tables.length) 
       recursive(); 
     }); 
    } 
0

如果你到整個異步Deferred事情:

var arr = [ 
    ["index.php/get/sync/riesgos", insert_riesgo, "riesgos"], 
    ["index.php/get/sync/estancias", insert_estancia, "estancias"], 
    ["index.php/get/sync/riesgosestancias", insert_riesgoestancia, "riesgosestancias"] 
]; 

var dfd = $.Deferred().resolve(); 

$.each(arr, function(i, item) { 
    dfd.then(function() { 
    return $.when(tableInsert(item[0], item[1], evalua.webdb.db, callback) 
    .then(function() { 
     update_records(item[2]); 
    }); 
    }) 
});