code

모든 jQuery Ajax 요청이 완료 될 때까지 기다리시겠습니까?

codestyles 2020. 10. 2. 22:21
반응형

모든 jQuery Ajax 요청이 완료 될 때까지 기다리시겠습니까?


모든 jQuery Ajax 요청이 다른 함수 내에서 완료 될 때까지 함수가 대기하도록하려면 어떻게해야합니까?

요컨대, 다음을 실행하기 전에 모든 Ajax 요청이 완료 될 때까지 기다려야합니다. 하지만 어떻게?


jQuery는 이제 이러한 목적 으로 언제 함수정의합니다 .

임의의 수의 Deferred 개체를 인수로 받아들이고 모든 개체가 해결되면 함수를 실행합니다.

즉, (예를 들어) 네 개의 ajax 요청을 시작한 다음 완료되면 작업을 수행하려면 다음과 같이 할 수 있습니다.

$.when(ajax1(), ajax2(), ajax3(), ajax4()).done(function(a1, a2, a3, a4){
    // the code here will be executed when all four ajax requests resolve.
    // a1, a2, a3 and a4 are lists of length 3 containing the response text,
    // status, and jqXHR object for each of the four ajax calls respectively.
});

function ajax1() {
    // NOTE:  This function must return the value 
    //        from calling the $.ajax() method.
    return $.ajax({
        url: "someUrl",
        dataType: "json",
        data:  yourJsonData,            
        ...
    });
}

제 생각에는 깨끗하고 명확한 구문을 만들고 페이지가 개발됨에 따라 원치 않는 부작용을 일으킬 수있는 ajaxStart 및 ajaxStop과 같은 전역 변수를 사용하지 않습니다.

기다려야하는 아약스 인수의 수를 미리 알지 못하는 경우 (즉, 가변 개수의 인수를 사용하려는 경우) 여전히 수행 할 수 있지만 조금 더 까다 롭습니다. $ .when ()에 Deferreds 배열 전달을 참조하십시오 (및 가변 인수 수로 문제를 해결할 때 jQuery .).

ajax 스크립트 등의 실패 모드에 대한 더 깊은 제어가 필요한 경우에서 반환 된 객체를 저장할 수 있습니다.이 객체는 모든 원래 ajax 쿼리를 포함 .when()하는 jQuery Promise 객체입니다. 당신은 호출 할 수 있습니다 .then()또는 .fail()자세한 성공 / 실패 처리기를 추가하도록합니다.


문서에서 모든 ajax 요청이 완료 될 때까지 기다리려면 얼마나 많은 요청이 있는지에 관계없이 $.ajaxStop다음과 같이 이벤트를 사용 하십시오.

  $(document).ajaxStop(function () {
      // 0 === $.active
  });

이 경우 향후에 완료 될 수있는 애플리케이션의 요청 수를 추측 할 필요가 없습니다. 어떤 경우에는 아약스 요청은 매우 (예 : 다른 함수를 호출) 복잡 할 수있는 함수의 내부 로직의 일부가 될 수 있고, 말했다 기능은 전체 로직을 수행하기보다는 때까지 그 경우에, 당신은 기다릴 수있는 유일한 대기 ajax완료 할 부분.

$.ajaxStop여기에서 HTML수정 될 수 있다고 생각 하는 모든 노드에 바인딩 할 수도 있습니다 ajax.

다시 말하지만이 핸들러의 목적은 무언가를 지우거나 재설정하지 않는 활성 이 없을 때를 아는 ajax것입니다.

PS ES6 구문을 사용해도 괜찮다면 Promise.all알려진 ajax방법을 사용할 수 있습니다 . 예:

Promise.all([ajax1(), ajax2()]).then(() => {
 // all requests finished successfully
}).catch(() => {
 // all requests finished but one or more failed
})

여기서 흥미로운 점은 함께 모두 작동한다는 것입니다 Promises$.ajax요청. 다음은 마지막을 보여주는 jsFiddle 입니다.


나는 정확히 내가 찾던 내 자신을 gnarf 하여 좋은 대답찾았 습니다. :)

jQuery ajaxQueue

//This handles the queues    
(function($) {

  var ajaxQueue = $({});

  $.ajaxQueue = function(ajaxOpts) {

    var oldComplete = ajaxOpts.complete;

    ajaxQueue.queue(function(next) {

      ajaxOpts.complete = function() {
        if (oldComplete) oldComplete.apply(this, arguments);

        next();
      };

      $.ajax(ajaxOpts);
    });
  };

})(jQuery);

그런 다음 다음과 같이 대기열에 ajax 요청을 추가 할 수 있습니다.

$.ajaxQueue({
        url: 'page.php',
        data: {id: 1},
        type: 'POST',
        success: function(data) {
            $('#status').html(data);
        }
    });

ajaxStop이벤트를 사용하십시오 .

예를 들어, 100 개의 ajax 요청을 가져 오는 동안 loading ... 메시지 가 있고 로드 된 메시지를 숨기려고한다고 가정 해 보겠습니다.

jQuery 문서에서 :

$("#loading").ajaxStop(function() {
  $(this).hide();
});

해당 페이지에서 수행되는 모든 ajax 요청을 기다립니다.


참고 : 위의 답변은이 답변이 작성 될 당시 존재하지 않았던 기능을 사용합니다. jQuery.when()이러한 접근 방식 대신 사용 하는 것이 좋지만 역사적인 목적으로 대답을 남겨 둡니다.

-

구현 방법은 코드에 따라 다르지만 간단한 세마포어를 사용하여 얻을 수 있습니다. 간단한 예는 다음과 같습니다.

var semaphore  = 0,     // counting semaphore for ajax requests
    all_queued = false; // bool indicator to account for instances where the first request might finish before the second even starts

semaphore++;
$.get('ajax/test1.html', function(data) {
    semaphore--;
    if (all_queued && semaphore === 0) {
        // process your custom stuff here
    }
});

semaphore++;
$.get('ajax/test2.html', function(data) {
    semaphore--;
    if (all_queued && semaphore === 0) {
        // process your custom stuff here
    }
});

semaphore++;
$.get('ajax/test3.html', function(data) {
    semaphore--;
    if (all_queued && semaphore === 0) {
        // process your custom stuff here
    }
});

semaphore++;
$.get('ajax/test4.html', function(data) {
    semaphore--;
    if (all_queued && semaphore === 0) {
        // process your custom stuff here
    }
});

// now that all ajax requests are queued up, switch the bool to indicate it
all_queued = true;

{async : false}처럼 작동하도록하고 싶지만 브라우저를 잠그고 싶지 않은 경우 jQuery 큐를 사용하여 동일한 작업을 수행 할 수 있습니다.

var $queue = $("<div/>");
$queue.queue(function(){
    $.get('ajax/test1.html', function(data) {
        $queue.dequeue();
    });
}).queue(function(){
    $.get('ajax/test2.html', function(data) {
        $queue.dequeue();
    });
}).queue(function(){
    $.get('ajax/test3.html', function(data) {
        $queue.dequeue();
    });
}).queue(function(){
    $.get('ajax/test4.html', function(data) {
        $queue.dequeue();
    });
});

자바 스크립트는 이벤트 기반이므로 기다리지 말고 후크 / 콜백을 설정하십시오.

jquery.ajax 의 성공 / 완료 방법을 사용할 수 있습니다.

또는 .ajaxComplete 사용할 수 있습니다 .

$('.log').ajaxComplete(function(e, xhr, settings) {
  if (settings.url == 'ajax/test.html') {
    $(this).text('Triggered ajaxComplete handler.');
    //and you can do whatever other processing here, including calling another function...
  }
});

좀 더 정확하게하기 위해 아약스 요청이 어떻게 호출되는지에 대한 의사 코드를 게시해야하지만 ...


약간의 해결 방법은 다음과 같습니다.

// Define how many Ajax calls must be done
var ajaxCalls = 3;
var counter = 0;
var ajaxCallComplete = function() {
    counter++;
    if( counter >= ajaxCalls ) {
            // When all ajax calls has been done
        // Do something like hide waiting images, or any else function call
        $('*').css('cursor', 'auto');
    }
};

var loadPersons = function() {
        // Show waiting image, or something else
    $('*').css('cursor', 'wait');

    var url = global.ctx + '/loadPersons';
    $.getJSON(url, function(data) {
            // Fun things
    })
    .complete(function() { **ajaxCallComplete();** });
};

var loadCountries = function() {
    // Do things
    var url = global.ctx + '/loadCountries';
    $.getJSON(url, function(data) {
            // Travels
    })
    .complete(function() { **ajaxCallComplete();** });
};

var loadCities = function() {
    // Do things
    var url = global.ctx + '/loadCities';
    $.getJSON(url, function(data) {
            // Travels
    })
    .complete(function() { **ajaxCallComplete();** });
};

$(document).ready(function(){
    loadPersons();
    loadCountries();
    loadCities();
});

희망이 유용 할 수 있습니다 ...


간단한 것이 필요하다면; 한 번 완료 콜백

        //multiple ajax calls above
        var callback = function () {
            if ($.active !== 0) {
                setTimeout(callback, '500');
                return;
            }
            //whatever you need to do here
            //...
        };
        callback();

또한 async.js 사용할 수 있습니다 .

시간 초과, SqlLite 호출 등과 같은 약속을 지원하지 않는 모든 종류의 비동기 호출을 병합 할 수 있고 아약스 요청뿐만 아니라 모든 종류의 비동기 호출을 병합 할 수 있기 때문에 $ .when보다 낫다고 생각합니다.


@BBonifield 답변을 기반으로 모든 ajax 호출에서 세마포어 논리가 확산되지 않도록 유틸리티 함수를 작성했습니다.

untilAjax 모든 ajaxCall이 완료되면 콜백 함수를 호출하는 유틸리티 함수입니다.

ajaxObjsajax 설정 객체의 배열입니다 [http://api.jquery.com/jQuery.ajax/].

fn 콜백 함수

function untilAjax(ajaxObjs, fn) {
  if (!ajaxObjs || !fn) {
    return;
  }
  var ajaxCount = ajaxObjs.length,
    succ = null;

  for (var i = 0; i < ajaxObjs.length; i++) { //append logic to invoke callback function once all the ajax calls are completed, in success handler.
    succ = ajaxObjs[i]['success'];
    ajaxObjs[i]['success'] = function(data) { //modified success handler
      if (succ) {
        succ(data);
      }
      ajaxCount--;
      if (ajaxCount == 0) {
        fn(); //modify statement suitably if you want 'this' keyword to refer to another object
      }
    };
    $.ajax(ajaxObjs[i]); //make ajax call
    succ = null;
  };

예 : doSomething함수는 untilAjax.

function doSomething() {
  // variable declarations
  untilAjax([{
    url: 'url2',
    dataType: 'json',
    success: function(data) {
      //do something with success data
    }
  }, {
    url: 'url1',
    dataType: 'json',
    success: function(data) {
      //do something with success data
    }
  }, {
    url: 'url2',
    dataType: 'json',
    success: function(response) {
      //do something with success data
    }
  }], function() {
    // logic after all the calls are completed.
  });
}

jQuery를 사용하면 ajax 요청을 비 동기화할지 여부를 지정할 수 있습니다. ajax 요청을 동기식으로 만들면 나머지 코드는 반환 될 때까지 실행되지 않습니다.

예를 들면 :

jQuery.ajax({ 
    async: false,
    //code
});

처음부터 시작하는 경우 $ .when () 사용을 적극 권장 합니다.

이 질문에 백만 개가 넘는 답변이 있지만 여전히 제 경우에 유용한 것을 찾지 못했습니다. 이미 일부 ajax 호출을하고있는 기존 코드베이스를 처리해야하고 promise의 복잡성을 도입하거나 전체를 다시 실행하고 싶지 않다고 가정 해 보겠습니다.

우리는 쉽게 jQuery를 활용할 수 있습니다 .data, .on그리고 .trigger영원히 이후 jQuery를의 한 부분이었다 기능.

Codepen

내 솔루션의 좋은 점은 다음과 같습니다.

  • 콜백이 정확히 무엇에 의존하는지는 분명합니다.

  • 함수 triggerNowOrOnLoaded는 데이터가 이미로드되었는지 또는 우리가 여전히 그것을 기다리고 있는지 상관하지 않습니다.

  • 기존 코드에 연결하는 것은 매우 쉽습니다.

$(function() {

  // wait for posts to be loaded
  triggerNowOrOnLoaded("posts", function() {
    var $body = $("body");
    var posts = $body.data("posts");

    $body.append("<div>Posts: " + posts.length + "</div>");
  });


  // some ajax requests
  $.getJSON("https://jsonplaceholder.typicode.com/posts", function(data) {
    $("body").data("posts", data).trigger("posts");
  });

  // doesn't matter if the `triggerNowOrOnLoaded` is called after or before the actual requests 
  $.getJSON("https://jsonplaceholder.typicode.com/users", function(data) {
    $("body").data("users", data).trigger("users");
  });


  // wait for both types
  triggerNowOrOnLoaded(["posts", "users"], function() {
    var $body = $("body");
    var posts = $body.data("posts");
    var users = $body.data("users");

    $body.append("<div>Posts: " + posts.length + " and Users: " + users.length + "</div>");
  });

  // works even if everything has already loaded!
  setTimeout(function() {

    // triggers immediately since users have been already loaded
    triggerNowOrOnLoaded("users", function() {
      var $body = $("body");
      var users = $body.data("users");

      $body.append("<div>Delayed Users: " + users.length + "</div>");
    });

  }, 2000); // 2 seconds

});

// helper function
function triggerNowOrOnLoaded(types, callback) {
  types = $.isArray(types) ? types : [types];

  var $body = $("body");

  var waitForTypes = [];
  $.each(types, function(i, type) {

    if (typeof $body.data(type) === 'undefined') {
      waitForTypes.push(type);
    }
  });

  var isDataReady = waitForTypes.length === 0;
  if (isDataReady) {
    callback();
    return;
  }

  // wait for the last type and run this function again for the rest of the types
  var waitFor = waitForTypes.pop();
  $body.on(waitFor, function() {
    // remove event handler - we only want the stuff triggered once
    $body.off(waitFor);

    triggerNowOrOnLoaded(waitForTypes, callback);
  });
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<body>Hi!</body>


모든 ajax로드가 완료되면 크기 확인을 사용하고 있습니다.

function get_ajax(link, data, callback) {
    $.ajax({
        url: link,
        type: "GET",
        data: data,
        dataType: "json",
        success: function (data, status, jqXHR) {
            callback(jqXHR.status, data)
        },
        error: function (jqXHR, status, err) {
            callback(jqXHR.status, jqXHR);
        },
        complete: function (jqXHR, status) {
        }
    })
}

function run_list_ajax(callback){
    var size=0;
    var max= 10;
    for (let index = 0; index < max; index++) {
        var link = 'http://api.jquery.com/ajaxStop/';
        var data={i:index}
        get_ajax(link,data,function(status, data){
            console.log(index)
            if(size>max-2){
                callback('done')
            }
            size++
            
        })
    }
}

run_list_ajax(function(info){
    console.log(info)
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>


Alex의 대답을 확장하기 위해 가변 인수와 약속이있는 예제가 있습니다. ajax를 통해 이미지를로드하고 모두로드 된 후 페이지에 표시하고 싶었습니다.

이를 위해 다음을 사용했습니다.

let urlCreator = window.URL || window.webkitURL;

// Helper function for making ajax requests
let fetch = function(url) {
    return $.ajax({
        type: "get",
        xhrFields: {
            responseType: "blob"
        },
        url: url,
    });
};

// Map the array of urls to an array of ajax requests
let urls = ["https://placekitten.com/200/250", "https://placekitten.com/300/250"];
let files = urls.map(url => fetch(url));

// Use the spread operator to wait for all requests
$.when(...files).then(function() {
    // If we have multiple urls, then loop through
    if(urls.length > 1) {
        // Create image urls and tags for each result
        Array.from(arguments).forEach(data => {
            let imageUrl = urlCreator.createObjectURL(data[0]);
            let img = `<img src=${imageUrl}>`;
            $("#image_container").append(img);
        });
    }
    else {
        // Create image source and tag for result
        let imageUrl = urlCreator.createObjectURL(arguments[0]);
        let img = `<img src=${imageUrl}>`;
        $("#image_container").append(img);
    }
});

단일 또는 다중 URL에서 작동하도록 업데이트 : https://jsfiddle.net/euypj5w9/


다른 답변에서 언급했듯이 ajaxStop()모든 ajax 요청이 완료 될 때까지 기다리는 데 사용할 수 있습니다 .

$(document).ajaxStop(function() {
     // This function will be triggered every time any ajax request is requested and completed
});

특정 ajax()요청에 대해 수행 complete()하려면 특정 ajax 요청 내에서 메소드를 사용하는 것이 가장 좋습니다 .

$.ajax({
    type: "POST",
    url: "someUrl",
    success: function(data) {
        // This function will be triggered when ajax returns a 200 status code (success)
    },
    complete: function() {
        // This function will be triggered always, when ajax request is completed, even it fails/returns other status code
    },
    error: function() {
        // This will be triggered when ajax request fail.
    }
});


그러나 몇 가지 특정 ajax 요청이 완료 될 때까지만 기다려야 한다면 ? 기다리려는 이러한 ajax가 완료 될 때까지 기다릴 멋진 자바 스크립트 약속사용하세요 . Promise가 ajax에서 어떻게 작동하는지 보여주기 위해 짧고 쉽고 읽기 쉬운 예제를 만들었습니다.
다음 예를 살펴보십시오 . 나는 setTimeout예를 명확히하기 위해 사용 했다.

// Note:
// resolve() is used to mark the promise as resolved
// reject() is used to mark the promise as rejected

$(document).ready(function() {
    $("button").on("click", function() {

        var ajax1 = new Promise((resolve, reject) => {
            $.ajax({
                type: "GET",
                url: "https://miro.medium.com/max/1200/0*UEtwA2ask7vQYW06.png",
                xhrFields: { responseType: 'blob'},
                success: function(data) {
                    setTimeout(function() {
                        $('#image1').attr("src", window.URL.createObjectURL(data));
                        resolve(" Promise ajax1 resolved");
                    }, 1000);
                },
                error: function() {
                    reject(" Promise ajax1 rejected");
                },
            });
        });

        var ajax2 = new Promise((resolve, reject) => {
            $.ajax({
                type: "GET",
                url: "https://cdn1.iconfinder.com/data/icons/social-media-vol-1-1/24/_github-512.png",
                xhrFields: { responseType: 'blob' },
                success: function(data) {
                    setTimeout(function() {
                         $('#image2').attr("src", window.URL.createObjectURL(data));
                         resolve(" Promise ajax2 resolved");
                    }, 1500);
                },
                error: function() {
                    reject(" Promise ajax2 rejected");
                },
            });
        });

        var ajax3 = new Promise((resolve, reject) => {
            $.ajax({
                type: "GET",
                url: "https://miro.medium.com/max/632/1*LUfpOf7teWvPdIPTBmYciA.png",
                xhrFields: { responseType: 'blob' },
                success: function(data) {
                    setTimeout(function() {
                         $('#image3').attr("src", window.URL.createObjectURL(data));
                         resolve(" Promise ajax3 resolved");
                    }, 2000);
                },
                error: function() {
                    reject(" Promise ajax3 rejected");
                },
            });
        });
        
        Promise.all([ajax1, ajax2, ajax3]).then(values => {
            console.log("We waited until ajax ended: " + values);
            console.log("My few ajax ended, lets do some things!!")
        }, reason => {
            console.log("Promises failed: " + reason);
        });
        
        // Or if you want wait for them individually do it like this
        // ajax1.then(values => {
        //    console.log("Promise 1 resolved: " + values)
        // }, reason => {
        //     console.log("Promise 1 failed: " + reason)
        // });
    });

});
img {
  max-width: 200px;
  max-height: 100px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button>Make AJAX request</button>
<div id="newContent">
    <img id="image1" src="">
    <img id="image2" src="">
    <img id="image3" src="">
</div>


나는이 문제를 만났고 그것을 해결하기 위해 일반 플러그인 jquery_counter를 만들었다 : https://bitbucket.org/stxnext/jquery_counter/


나는 간단한 방법을 찾았습니다. shift()

function waitReq(id)
{
  jQuery.ajax(
  {
    type: 'POST',
    url: ajaxurl,
    data:
    {
      "page": id
    },
    success: function(resp)
    {
      ...........
      // check array length if not "0" continue to use next array value
      if(ids.length)
      {
        waitReq(ids.shift()); // 2
      )
    },
    error: function(resp)
    {
      ....................
      if(ids.length)
      {
        waitReq(ids.shift());
      )
    }
  });
}

var ids = [1, 2, 3, 4, 5];    
// shift() = delete first array value (then print)
waitReq(ids.shift()); // print 1

내 솔루션은 다음과 같습니다.

var request;
...
'services': {
  'GetAddressBookData': function() {
    //This is the primary service that loads all addressbook records 
    request = $.ajax({
      type: "POST",
      url: "Default.aspx/GetAddressBook",
      contentType: "application/json;",
      dataType: "json"
    });
  },

  ...

  'apps': {
    'AddressBook': {
      'data': "",
      'Start': function() {
          ...services.GetAddressBookData();
          request.done(function(response) {
            trace("ajax successful");
            ..apps.AddressBook.data = response['d'];
            ...apps.AddressBook.Filter();
          });
          request.fail(function(xhr, textStatus, errorThrown) {
            trace("ajax failed - " + errorThrown);
          });

아주 잘 작동했습니다. 이 작업을 수행하는 여러 가지 방법을 시도했지만 이것이 가장 간단하고 재사용이 가능하다는 것을 알았습니다. 도움이되기를 바랍니다.


내 솔루션을 살펴보십시오.

1.이 함수 (및 변수)를 javascript 파일에 삽입합니다.

var runFunctionQueue_callback;

function runFunctionQueue(f, index, callback) {

  var next_index = index + 1

  if (callback !== undefined) runFunctionQueue_callback = callback;

  if (f[next_index] !== undefined) {
    console.log(index + ' Next function avalaible -> ' + next_index);
    $.ajax({
      type: 'GET',
      url: f[index].file,
      data: (f[index].data),
      complete: function() {
        runFunctionQueue(f, next_index);
      }
    });
  } else {
    console.log(index + ' Last function');
    $.ajax({
      type: 'GET',
      url: f[index].file,
      data: (f[index].data),
      async: false,
      complete: runFunctionQueue_callback
    });
  }
}

2. 다음과 같이 요청으로 어레이를 구축합니다.

var f = [
           {file: 'file_path', data: {action: 'action', data: 'any_data}},
           {file: 'file_path', data: {action: 'action', data: 'any_data}},
           {file: 'file_path', data: {action: 'action', data: 'any_data}},
           {file: 'file_path', data: {action: 'action', data: 'any_data}}
        ];

3. 콜백 함수 생성 :

function Function_callback() {
  alert('done');
}

4. 매개 변수와 함께 runFunctionQueue 함수를 호출합니다.

runFunctionQueue(f, 0, QuestionInsert_callback);
// first parameter: array with requests data
// second parameter: start from first request
// third parameter: the callback function

$.whenhttps://stackoverflow.com/a/13455253/10357604에 설명 된대로 작동하는 callback(x)대신 나를 위해 작동하지 않습니다 return x.


Alex가 제공 한 솔루션이 잘 작동합니다. 같은 개념이지만 조금 다른 방식으로 사용 (통화 횟수를 미리 알 수없는 경우)

http://garbageoverflow.blogspot.com/2014/02/wait-for-n-or-multiple-or-unknown.html


이 방법을 시도하십시오. ajax 호출이 끝날 때까지 기다리도록 자바 스크립트 함수 내부에 루프를 만듭니다.

function getLabelById(id)
{
    var label = '';
    var done = false;
    $.ajax({
       cache: false,
       url: "YourMvcActionUrl",
       type: "GET",
       dataType: "json",
       async: false,
       error: function (result) {
         label='undefined';
         done = true;
        },
       success: function (result) {
            label = result.Message;
            done = true;
        }
     });

   //A loop to check done if ajax call is done.
   while (!done)
   {
      setTimeout(function(){ },500); // take a sleep.
   }

    return label;
}

참고 URL : https://stackoverflow.com/questions/3709597/wait-until-all-jquery-ajax-requests-are-done

반응형