我有以下代码
$.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");
});
});
});
我正在尝试找到如何将它集成到 for 循环或 $.each 循环中,以便它在下一次迭代之前等待 promise 完成。乍一看嵌套3个调用会更容易,但这只是一段代码,现在嵌套调用数为15!
最佳答案
嗯,你首先需要一个包含数据的数组,例如:
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
。
关于javascript - 循环延迟对象和 promise ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12703303/