Search code examples
javascriptajaxhttpxmlhttprequest

Parallel AJAX request without jQuery


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.


Solution

  • 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));