微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

JavaScript - 等待多个 ajax 请求完成然后做一些事情

如何解决JavaScript - 等待多个 ajax 请求完成然后做一些事情

我在 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',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>

解决方法

将$.ajax返回的promise保存在变量中,并使用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;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。