我有以下代码
$.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");
});
});
});
Run Code Online (Sandbox Code Playgroud)
我试图找到如何将它集成在for循环或$ .each循环中,以便它等待在下一次迭代之前完成的承诺.起初看起来三个调用更容易嵌套,但这只是一段代码,嵌套调用现在算了15个!
好吧,你需要一个首先包含数据的数组,例如:
var calls = [
{
url: "index.php/get/sync/riesgos",
func: insert_riesgo,
update: "riesgos"
},
...
];
Run Code Online (Sandbox Code Playgroud)
然后你可以使用.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);
]);
});
});
Run Code Online (Sandbox Code Playgroud)
$.when在您的示例中没有必要.