0

I am trying to fetch multiple parallel request with single callback, just like jQuery "when"

$.when(ajax1, ajax2).done(callback)

I don't want to call the second ajax call after ajax1 is completed, I want ajax2 and ajax2 to be requested same time and than the callback when both are completed.

I'm looking for plain javascript instead of jQuery for such implementation.

MZH
  • 1,414
  • 4
  • 29
  • 57

3 Answers3

1

Use a method to make the request that will return a promise.

This could be simply using the fetch api or wrapping XMLHttpRequest with a promise.

Put the two promises in an array and pass it to Promise.all.

Promise.all([ fetch("http://example.com"), fetch("http://example.net") ])
    .then(array => console.log(array));
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
0

You can also use async/ await with Promise.all to achieve that:

async function getAll() {
  // waits untill all resposnes are resolved
  const data = await Promise.all([
    fetch('https://jsonplaceholder.typicode.com/todos/1').then(response =>
      response.json()
    ),
    fetch('https://jsonplaceholder.typicode.com/todos/2').then(response =>
      response.json()
    ),
  ]);
  // returns array of resolved data from fetch
  console.log(data);
}

getAll()
maaajo
  • 839
  • 6
  • 10
-2

You can replace done to then Method

$.when( ajax1 , ajax2 ).then(function() {
    // success ajax1, success ajax 2
});