簡體   English   中英

jQuery 異步 ajax 調用

[英]jQuery async ajax calls

我有以下代碼,其中包含一個列表,並且對於此列表中的每個元素,執行 ajax 調用。

util.testMethod = function(list) {

            var map = new Map();

            list.forEach(function(data) {
                $.ajax({
                    url: 'https://......',
                    type: 'GET',
                    data: // data needed here
                    success: function(data) {
                        // do something
                    },
                    error: function(jqxhr, settings, exception) {
                        // dos omething
                    }
                });
            });


            return map;
        };

由於我進行了多個異步 ajax 調用,因此我們假設其中 1 個需要很長時間才能執行。 這個 testMethod 是否有可能在 ajax 調用完成之前返回?

確實。 ajax 調用是異步的,因此代碼將繼續執行而無需等待成功/錯誤回調函數。

您有兩個選擇:

  1. 將您的 ajax 調用作為同步調用(更多信息在這里
  2. (推薦)使您的testMethod函數成為異步函數(更多信息在這里

但是(1º 選項)

不推薦將 async 屬性設置為 false 並正在被刪除(鏈接)。 如果你使用這個,包括 Firefox 和 Chrome 在內的許多瀏覽器已經開始在控制台中打印警告:

並遵循了2º選項的例子(更多關於JavaScript的承諾,在這里和Promise.All在這里):

 async function makeAjaxCall() { return new Promise((resolve) => { setTimeout(() => { // Just to make the makeAjaxCall 1 second slower; $.ajax({ url: 'http://www.mocky.io/v2/5e6ac7d32d0000db0c5fa686', type: 'GET', data: {}, success: function(data) { resolve(data); }, error: function(jqxhr, settings, exception) { resolve({ error: 'OMG an ERROR!'}); // dos omething } }) }, 1000); }); }; async function asynCall() { for(let i=0; i<10; i++) { // You can see in here that will wait 1 second before is going to the next ajax call const result = await makeAjaxCall(); console.log(result); } } // You can run all your calls in paralel by using the Promise.All like this async function promiseAll() { const ajaxCalls = []; for(let i=0; i<10; i++) { ajaxCalls.push(makeAjaxCall()); } //for this case, the calls will be made in parallel, which measn will take slight more than 1 second Promise.all(ajaxCalls).then(function(values) { // will print the array of values which contains the values of each ajax call console.log(values); }); } asynCall(); promiseAll();
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM