如何使 ajax 同步而不是使用 async:false?

我在使用 ajax 异步时遇到了一些问题。我有一个数组,然后循环遍历该数组以进行 ajax 调用,如果成功,ajax 将返回一个 xml 字符串,我将使用它来填充表格并更新进程栏。我用async:false它在 Firefox 上运行良好,但在 Chrome 上运行不正常。我也试过用$.ajax().done(),但一点影响都没有。


当 ajax 调用完成然后下一个循环将运行时,是否无论如何要获取响应的 xml 字符串?


for (var i = 0; i <= arr.length; i++){

    $.ajax({

        url: '',

        data: '',

        async: false

    }).done(function(xml) {

       //get xml string to handle and put it into some table as contents

    });

    //Then go to next loop

}


慕的地6264312
浏览 224回答 3
3回答

红糖糍粑

不要试图使异步代码同步。您将锁定事件循环并受到严重的性能损失。并行发出请求。将承诺收集在一个数组中。用于Promise.all确定它们何时全部完成。然后你可以从它们中提取数据并用它做你想做的事。例如:const baseUrl = "https://jsonplaceholder.typicode.com/users/";const userIds = [1,2,3,4,5];const completeUrls = userIds.map( id => `${baseUrl}${id}` );const promises = completeUrls.map( url => jQuery.ajax({url}) );const collectedDataPromise = Promise.all(promises);collectedDataPromise.then( data => {&nbsp; &nbsp; const names = data.map( user => user.name );&nbsp; &nbsp; const ul = $("<ul />");&nbsp; &nbsp; names.forEach( name => {&nbsp; &nbsp; &nbsp; &nbsp;ul.append( $("<li>").text(name) );&nbsp; &nbsp; });&nbsp; &nbsp; $("body").append(ul);});<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

智慧大石

最后,我得到了我自己的解决方案,我使用 async/await 来理解。async function ajaxGetData(){&nbsp; &nbsp; return $.ajax({&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;url: '',&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;data: ''&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }).then(response => response.data);}async function hanldeResponse(){&nbsp; &nbsp;var arr = [1,2,...];&nbsp; &nbsp;for(var i = 0; i < arr.length; i++){&nbsp; &nbsp; &nbsp; &nbsp;let res = await ajaxGetData();&nbsp; &nbsp; &nbsp; &nbsp;//some code to handle the response with res variable&nbsp; &nbsp;}}

慕田峪4524236

如果你必须在每次迭代中更新数据,你可以使用一些字符串并在 .done() 中更新。像这样递归试试:var counter = arr.length;function callAjax() {&nbsp; if (counter) {&nbsp; &nbsp; $.ajax({&nbsp; &nbsp; &nbsp; url: '',&nbsp; &nbsp; &nbsp; data: ''&nbsp; &nbsp; })&nbsp; &nbsp; .done(function(xml) {&nbsp; &nbsp; &nbsp; //get xml string to handle and put it into some table as contents&nbsp; &nbsp; &nbsp; counter--;&nbsp; &nbsp; &nbsp; callAjax();&nbsp; &nbsp; });&nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go