How should one parallelize the execution of two or more json calls?

I am trying to optimize the load time of a web page and am running into a puzzle. After doing some JSP refactoring and reducing the client benefits that were actually needed on the web page, I was able to optimize load times.

enter image description here

However, I noticed that there are 3 json calls that are happening (see screenshot) and I need to parallelize their execution. As you can see, there are three json calls originating from the page. For example, the first two (in blue box) load the left div and the top div inside the page (for example to load some themes / groups and notifications). The last call (in red box) downloads wall posts (facebook type) and this only happens after the above two calls are completed.

I want all three json calls to run (or load the page) at the same time, i.e. parallel. Can anyone here suggest me how should I do this?

Thank:)

+3


source to share


1 answer


What you need to do is just make each call together, and if you want to wait until all of them are complete before doing anything else, keep the promises.

Example:

$q.all([getThing1().promise, getThing2().promise(), getThing3().promise]).then(function() {
  // Do other stuff once all 3 have finished.
});

      

Here's a working example:



// https://developers.google.com/web/fundamentals/getting-started/primers/promises#promisifying_xmlhttprequest
function get(url) {
  return new Promise(function(resolve, reject) {
    var req = new XMLHttpRequest();
    req.open('GET', url);
    req.onload = function() {
      if (req.status == 200) {
        resolve(req.response);
      }
      else {
        reject(Error(req.statusText));
      }
    };
    req.onerror = function() {
      reject(Error("Network Error"));
    };
    req.send();
  });
}

document.querySelector('button').addEventListener('click', function() {
  Promise.all([get('https://httpbin.org/get?a=1'), 
               get('https://httpbin.org/get?b=2'), 
               get('https://httpbin.org/get?c=3')]).then(values => { 
    console.log(values);
  });
});
      

<button>get</button>
      

Run codeHide result


In the Network pane, you can see that all three requests are being executed simultaneously: devtools screenshot of concurrent requests

+2


source







All Articles