【问题标题】:JavaScript - Wait until multiple ajax requests are done then do somethingJavaScript - 等到多个 ajax 请求完成然后做一些事情
【发布时间】:2021-06-25 01:03:26
【问题描述】:

我在 JavaScript 中有两个 ajax 调用,它们以异步方式向页面添加内容。我需要创建一个“超时”函数(或类似的东西),等待它们都完成加载,然后执行更多代码。这是我目前所拥有的

https://jsfiddle.net/qcu5asnj/

<div class='resultsSection'>
    Example
</div>

<script>

var loading_first = "loading";
var first_ajax = {
  url: 'https://example.com/load.php?q=fast',
  type: "GET",
  success: function( data ) {
        console.log("success");
         $(".resultsSection").append(data);
         loading_first = "done";
  }
};
$.ajax( first_ajax );

var loading_second = "loading";
var second_ajax = {
  url: 'https://example.com/load.php?q=slow',
  type: "GET",
  success: function( data ) {
        console.log("success");
        $(".resultsSection").append(data);
        loading_second = "done";
  }
};
$.ajax( second_ajax );

// Need to create a function that waits until both are done. I know this is wrong
if((loading_first == "done") && (loading_second == "done")){
        console.log("Both done loading, execute more code here");
}

</script>

【问题讨论】:

    标签: javascript html jquery ajax timeout


    【解决方案1】:

    将 $.ajax 返回的承诺存储在变量中并使用 Promise.all()

    const req1 = $.ajax('https://jsonplaceholder.typicode.com/todos/1').then(data => {
      console.log('First request done')
      return data
    })
    
    const req2 = $.ajax('https://jsonplaceholder.typicode.com/todos/2').then(data => {
      console.log('Second request done')
      return data
    })
    
    Promise.all([req1, req2]).then(results=>{
       console.log('All done')
       console.log('Combined results',results)
    }).catch(err=> console.log('Ooops one of the requests failed'))
    .as-console-wrapper {max-height: 100%!important;top:0;}
    &lt;script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"&gt;&lt;/script&gt;

    【讨论】:

    • 不幸的是我不能使用这种方法。我的例子被简化了,但是用我的代码我不能这样做。还有其他方法吗?
    • 好吧,即使这些请求是在单独的函数中完成的,您也可以从这些函数返回相同的 Promise 并以这种方式执行。无论代码复杂度如何,这是最实用的方法
    猜你喜欢
    • 2011-10-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多