Contact Form

Name

Email *

Message *

Cari Blog Ini

Javascript Promise Ajax Post Example

How to Promisify an Ajax Call

By Michael Soriano

February 11, 2017

jQuery's implementation of making AJAX calls is quite easy to understand. There is ajax.get, ajax.post, and so on. These functions return a Promise object, which can be used to wait for the AJAX call to complete.

However, what if you have an AJAX call and some other function that depends on the AJAX call loading before it runs? In this case, you can use the Promise.all function to wait for all of the AJAX calls to complete before proceeding.

Here is an example of how to use Promise.all:

``` function fetchMe(url) { return new Promise((resolve, reject) => { $.ajax({ url: url, success: function(data) { resolve(data); }, error: function(jqXHR, textStatus, errorThrown) { reject(errorThrown); } }); }); } Promise.all([fetchMe('url1'), fetchMe('url2'), fetchMe('url3')]).then((values) => { // All of the AJAX calls have completed. // The `values` array contains the data returned from each of the AJAX calls. }); ```

In this example, fetchMe returns the Promise from the AJAX call. Using when, we tell the script to wait for all three of these to complete before proceeding to the then.


Comments