javascript - 循环延迟对象和 promise

标签 javascript jquery

我有以下代码

    $.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/

相关文章:

javascript - 收到错误 "has no method ' 包含“”

javascript - 在月 View 中剪切事件的结束时间

javascript - TinyMCE & MoxieManager : url from MoxieManager won't be passed to TinyMCE

javascript - 是否可以在一个数组中对 Jekyll Collection 和 Jekyll Data 进行排序?

jquery - 表单日期输入字段格式

javascript - Parse.com 云代码访问查询结果中的用户对象为 null

javascript - 关闭弹出子窗口后在父页面中显示消息

javascript - async await node.js 跳过第二个 await 语句保存 mongodb

Jquery On 而不是 Live 用于动态输入

javascript - 如何检测具有相同 ID 的已单击 div 文本