Differences between nested AJAX and promises

16

In another question of StackOverflow in Spanish is done reference to nested AJAX calls and the response suggests using promises instead of nesting AJAX calls. And from there I have some doubts.

Note: I'm going to use jQuery notation by eliminating enough parameters and renaming the functions to make it easier to read. It does not mean that this question is about jQuery or AJAX in jQuery.

Basically what the question asks is this:

Structure A

$.ajax({
    url: URL1,
    success: function() {
        a1();
        $.ajax({
            url: URL2,
            success: function() {
                a2();
            },
            error: function() {
                b2();
            }
        });
    },
    error: function() {
        b1();
    }
});

And what is suggested in the answer is something like this:

Structure B

var promise = $.ajax({
    url: URL1,
    success: function() {
        a1();
    },
    error: function() {
        b1();
    }
});

promise.then(function() { 
    $.ajax({
        url: URL2,
        success: function() {
            a2();
        },
        error: function() {
            b2();
        }
    });
});

And now my doubts:

  • Are structures A and B equivalent? What is the difference between them?
  • Is there any advantage to using one over the other?
  • Is one of the recommended methods on the other?
asked by Alvaro Montoro 02.02.2016 в 23:53
source

2 answers

15

The difference lies in the ease of maintenance, and in the handling of errors. It is also much easier to debug

Promises allows you to maintain immutability in your methods, derived from functional programming, while with callbacks it is more imperative.

Another advantage is that promises is native to JS, since Unlike the option of Jquery , it's a standard.

It also prevents you from escaping the callback hell XD

In relation to the structures that you mention in your question, the part of promises would modify it a bit so that it would be equivalent

new Promise(function(resolve, reject) {
      $.ajax({
          url: URL1,
          success: function(data) { // si recibo algún dato como parametro
            resolve(data); //Resuelvo la promesa (la cumplo) y con esto se puede recibir como parámetro 
            a1();
          },
          error: function(CausaDelError) {
            reject(CausaDelError); //marco la promesa como incumplida y paso como parámetro el porque no se cumplió
            b1();
          };
        })
        .then(function() { //Notese que no necesito declarar la variable
          $.ajax({
            url: URL2,
            success: function() {
              a2();
            },
            error: function() {
              b2();
            }
          });
        })
        .catch(function(error) {
          //Capturo los errores posibles en la primer promesa o en la segunda (then)
          console.log(error);
        });

Udacity has a very short free course that explains promises very easily and quickly p>     

answered by 03.02.2016 / 00:21
source
4

This does not answer any of your three questions, but as an alternative here you have a native tool in JavaScript relatively recently, Fetch API , which may require a polyfill to certain browsers and uses Promises.

const url 		= 'https://api.myjson.com/bins/3ko1q',
      method 	= 'GET',
      headers   = new Headers({'Content-Type' : 'application/json'});
      
const req = new Request(url, { method, headers });

fetch(req)
  .then( res => res.ok ? res.json() : undefined )
  .then( data => JSON.stringify(data) )
  .then(alert)
  .catch(console.error.bind(console));
    
answered by 22.08.2016 в 14:19