【问题标题】:How to execute code after finishing all $.getJSON calls, including inner ones, and ones in loops?如何在完成所有 $.getJSON 调用(包括内部调用和循环调用)后执行代码?
【发布时间】:2019-07-08 08:17:24
【问题描述】:

我有这个代码。

$.getJSON("/some-path.json",function(resultArray){
  for (var j = resultArray.length - 1; j >= 0; j--){
    $.getJSON(resultArray[j],function(resultObject){
      // Bunch of stuff happens here
    });
  }
}).done(function(){
  // This should execute only after ALL $.getJSON codes above finish
});

但是.done() 中的代码在所有.getJSON() 内容完成之前运行。我如何让.done() 中的代码在.getJSON() 内容完成后执行?

【问题讨论】:

    标签: javascript jquery getjson


    【解决方案1】:

    我会使用async/await 语法,并使用Promise.all 等待所有内部提取完成:

    (async () => {
      const resultArray = await $.getJSON("/some-path.json");
      await Promise.all(resultArray.map(
        url => $.getJSON(url, (innerResult) => {
          // Bunch of stuff happens here
        })
      ));
      // all inner results have completed
    })();
    

    【讨论】:

      猜你喜欢
      • 2018-01-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-25
      • 1970-01-01
      • 2012-07-01
      • 1970-01-01
      相关资源
      最近更新 更多