Multiple AJAX calls without blocking

收藏待读

Multiple AJAX calls without blocking

I run a function called checker every 60 seconds like so:

setInterval( checker, 60 * 1000 );

checker has an array of URLs which it checks via AJAX, the current code is like this:

$.ajax({
  url: sites[i].url,
  type: "GET",
  dataType: "json",
  async: false,
  success: function(data){
     //blah blah blah
  }else{
     //something else
  },
  error: function(){
    //blah blah blah
  }
});

The code works, changes some UI based stuff depending on the results of the JSON. My problem is that the execution time for this checking several sites is ~4 seconds, at which point the page becomes unresponsive for this time. If I remove async: false the code no longer works as expected.

Someone mentioned using callbacks to solve the problem but don’t understand how to use them in this context.

EDIT

Updated code based upon suggestion from adosan:

function promtest(){
    var sites = [
             { name: "WorkingSite", url: "http://sitename.com/testing.php" },
             //a bunch more sites, 1 returns a 404 to test for failure
             { name: "404Site", url: "http://404url.com/testing.php" }
             ];

    var promiseList = [];
    for(var i in sites){
    var promise = $.ajax({
    url: sites[i].url,
    type: "GET",
    dataType: "json",
    async: true,
    success: function(data){

      if( data.Response != 'OK' ){
        console.log('Site ' + sites[i].name + ' Not OK' );
      }else{
        console.log( 'Site ' + sites[i].name + ' OK ');
      }
    },

    failure: function(data){
      console.log('Failure for site: ' + sites[i].name);
    },

    error: function(){
      console.log('Site ' + sites[i].name + ' Not OK' );
    }

    });

    promiseList.push(promise);
    }

    $.when.apply($, promiseList).then(function(){console.log('success')}, function(){console.log('fail')});

}

In the console I see:

Site 404Site Not OK
Site 404Site Not OK
Site 404Site Not OK
Site 404Site Not OK
Site 404Site Not OK
Site 404Site Not OK
Site 404Site Not OK
fail
Site 404Site Not OK
Site 404Site Not OK
Site 404Site Not OK
Site 404Site Not OK

Note that the site name is always showing as the last one on the list.

You may use Promise ( https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise ) here. Example:

function checker(url) {
    return new window.Promise(function (resolve, reject) {

        function successCallback(response) {
            resolve(response);
        }

        function errorCallback(response) {
            reject(response);
        }

        $.ajax({
            data: data,
            dataType: 'JSON',
            type: 'GET',
            url: url
        })
        .done(successCallback)
        .fail(errorCallback);
    });
}

function checkerSuccess(response) {
    console.log(response);
}

function checkerError(error) {
    console.warn(error);
}

checker('http://api.example.com').then(checkerSuccess).catch(checkerError);

原文 : Hello, buddy!

相關閱讀

免责声明:本文内容来源于Hello, buddy!,已注明原文出处和链接,文章观点不代表立场,如若侵犯到您的权益,或涉不实谣言,敬请向我们提出检举。