繁体   English   中英

延迟 jquery ajax

[英]Deferred jquery ajax

我想我已经浏览了所有关于此的问题。

我有一个函数,它使用 jquery 通过 ajax 更新记录。 我需要更改它以执行它们并等待每个完成。

我一直在阅读$.Deferred并尝试实现,但代码仍然没有等待。 我知道 ajax 是异步的,我不想改变它,但我确实希望它等待,因为代码输出消息并且我需要它们。

我的代码是这样的:

//do the export:
function doExport(id) {

var exportComplete = $.Deferred();

var exportPromise = $.ajax({
    type: "POST",
    url: "import.php",
    dataType: "json",
    data: { id: id }
});

exportPromise.done(function(msg) {
    //msg contains the text from the import
    exportComplete.resolve(msg);
});

return exportComplete.promise();
}

//export all ticked items (from a list)
function importInvoices() {

    var checked = new Array;
    $('#apiCall').html("");

    //put all checked items into an array (id corresponds to a PK in the db)
    $("input[name=selectedRow]:checked").each(function(num,row) {
        checked.push($(row).data('id'));
    });

    //loop through each checked item
    $(checked).map(function(num, id) {
console.log("starting " + id)            ;
        var prom = doExport(id).then(function(result) {
console.log("done " + id);
            
            $('#apiCall').html($("#apiCall").html() + result.messages);
        
        });
    });

    $("#pleaseWaitContainer").hide();

}

它一定很近,但我想我遗漏了什么或在错误的地方。 结果导出的文本确实出现在它应该出现的位置,但是如果(例如)我选择了 3 张发票,我会得到 3 次“开始 xxx”的控制台文本,然后是“完成 xxx”四次。

像这样:

starting 243
starting 663
starting 823
done 243
done 663
done 823

而我想要的是

starting 243
done 243
starting 663
done 663
starting 823
done 823

任何建议将不胜感激......我正在撕掉我有限的头发。

克里斯

呼叫成功

const checked = $("input[name=selectedRow]:checked").map(function() {
  return $(this).data('id'))
}).get()
const load = function() {
  $.ajax({
    url: `/someprocess.php?id=${checked.shift()}&otherparm=bla`,
    success: function() {
      if (checked.length > 0) load()
    }
  })
}

if (checked.length > 0) load(); // start

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM