Trigger start after receiving multiple json files asynchronously

I have 3 JSON files from an old forum that contains: members, topics and answers. Now I want to display it on a website, getting 3 json files via javascript / jquery.

I could do it synchronously, first getting the participants, returning, getting topics and returning answers. But I want to do this asynchronously.

Is there something like $ .getJson that takes multiple urls and then returns an array of results? Like imaginary $ .getJson ([url1, url2, url3], callBackFunction)

+4
source share
3 answers

Use jQuery.when :

var A = $.getJSON(url1);
var B = $.getJSON(url2);
var C = $.getJSON(url3);

$.when(A,B,C).done(function(aResult, bResult, cResult){//when all request are successful
    console.log([aResult[0],bResult[0],cResult[0]]);
});
+5

, - $.when. promises , . promises $.when apply. :

var endpoints = [url1, url2, url3];
var promises = [];

// Simple function that takes an endpoint and returns a promise.
// I've used $.ajax here, but all of jQuery's
// XHR objects use the promise interface
function getData(endpoint) {
  return $.ajax({
    type: 'GET',
    url: endpoint,
    dataType: 'jsonp'
  });
}

// Build an array of promises.
for (var i = 0, l = endpoints.length; i < l; i++) {
  promises.push(getData(endpoints[i]));
}

// Pass the promises to `$.when`. Show the returned data when
// the promises have all finished processing.
$.when.apply(null, promises).then(function (data1, data2, data3) {
  console.log(data1, data2, data3);
});
+1

jQuery, $.getJson() . , , . , .

:

console.log( "loading first file..." );
$.getJSON( "file1.js", function( json ) {
  console.log( "first file loaded!" );
});

console.log( "loading second file..." );
$.getJSON( "file2.js", function( json ) {
  console.log( "second file loaded!" );
});

console.log( "loading third file..." );
$.getJSON( "file3.js", function( json ) {
  console.log( "third file loaded!" );
});

, , 1/2/3 .


What you could do is that all callbacks perform the same function that will store the count of the number of loaded resources, after all of them have been loaded, you can then call your last callback:

$.getJSON( "file.js", function( json ) {
  // Do whatever you want with the `json` parameter
  resource_loaded(); // monitor loaded resources.
});

var total_resources = 0
var loaded_resources = 0;
function resource_loaded(){
  loaded_resources += 1;
  if ( loaded_resources === total_resources ){
    final_callback();
  }
}
-1
source

Source: https://habr.com/ru/post/1532115/


All Articles