0

I'd like to get many JSONs by Javascript or JQuery, and pull of elements named j_name, j_value, and j_sts into sarr[i], rarr[i], and parr[i], respectively.

var sarr = new Object;
var rarr = new Object;
var parr = new Object;

//num_json is the number of JSONs
//jsonurl is a url of the JSON
for(var i = 1; i < num_json; i++){
$.ajaxSetup({async: false});
  $.getJSON(jsonurl[i], function(data) {
    sarr[i] = data.j_name;
    rarr[i] = data.j_value;
    parr[i] = data.j_sts;
  });
$.ajaxSetup({async: true});
}

Without

$.ajaxSetup({async: false});

and

$.ajaxSetup({async: true});

, an asynchronous processing causes that sarr[i], rarr[i], and parr[i] are filled by current loaded JSON elements. I have to stop asynchronous loading. However, this process is very slow to display the page.

I'd like to do like following to separate the object "data" storing a JSON, but it's clearly invalid.

var sarr = new Object;
var rarr = new Object;
var parr = new Object;
var data = new Object;

for(var i = 1; i < num_json; i++){
  $.getJSON(jsonurl[i], function(data[i]) {
    sarr[i] = data[i].j_name;
    rarr[i] = data[i].j_value;
    parr[i] = data[i].j_sts;
  });
}

How can I load many JSONs asynchronously and store each specific elements?

  • Using closures is one way, https://stackoverflow.com/questions/111102/how-do-javascript-closures-work?rq=1 – Adrian Sep 01 '17 at 14:32

1 Answers1

1

Here is a way to do it

const urls = [];

const responses = urls.map( url => fetch(url).then(res => res.json()) );
Promise.all(responses)
    .then( dataArr => {

        return dataArr.reduce((res, data) => {
            res.sarr[i] = data[i].j_name;
            res.rarr[i] = data[i].j_value;
            res.parr[i] = data[i].j_sts;
            return res;
        }, { sarr: [], rarr: [], parr: [] });

    } )
.then(result => {

    const { sarr, rarr, parr } = result;

});

This solutions uses the fetch API and Promises. Basically what it does is : given an array of urls, make a request for each urls and retrieve the result as json, store the result in an array of Promises. Given this array of promises, once all are settled, retrieve the result if and only if all requests were successful. If they are successful then store each values in the correct array and return it.

adz5A
  • 2,012
  • 9
  • 10