JavaScript – How to Handle Multiple API Calls Using jQuery

javascriptjquery

I need to build a service that will call multiple API's at the same time and then output the results on the page (Think of how a price comparison site works for example).

The idea being that as each API call completes the results are sent to the browser immediately and the page would get progressively bigger until all process are complete.

Because these API calls may take several seconds each to return I would like to do this via javascript/jquery in order to create a better user experience. I have never done anything like this before using javascript/jquery so I was wondering if there was any frameworks/advice that anyone would be willing to share.

Best Answer

That should be pretty easy, considering this is the way JavaScript HTTP requests work by default!

Unless you specifically tell XMLHttpRequest(or jQuery's $.ajax or one of it's wrappers) to be synchronous, it'll run at asynchronous mode. That means you give it a callback function, it sends the request, and then continue in the code. Only when the response returns the callback gets invoked with it - that can happen long after the JavaScript event that sent the request ended.

So, what you simply need to do is(shown in jQuery for simplicity, but the concept for pure JS is the same):

$.ajax({
        type: 'POST',//or 'GET'
        url: 'first_api_url',
        data: {/*first_api_data*/}
}).done(function(data){
        //Data contains the results from the first API.
        //Use them to update the DOM.
});

$.ajax({
        type: 'POST',//or 'GET'
        url: 'second_api_url',
        data: {/*second_api_data*/}
}).done(function(data){
        //Data contains the results from the second API
        //Use them to update the DOM.
});

P.S. - you shouldn't count about the second call being sent before the first call's response returns. If the first call's response returns really really fast, it might interrupt in the middle. It's probably depends on the JavaScript implementation, and it's probably not going to happen in this particular code when the second call is immediately after the first, but I've encountered a nasty bug where AJAX calls return too fast and uses things before they're initialized.