Difference between Promise and callback

Asked

Viewed 4,398 times

13

I would like to understand a little better the advantages of using Promise!

today I use callback function. Ex:

function a(callback) {
   $.ajax({
   ...
   })
   .done(function(data){
      callback(data)
   })
   .fail(function(data){
      callback(data)
   });
}

function b() {
   a(function(response){
     console.log(response)
   });
}

Already with Promise, it would be something like this:

var promise = new Promise(function(resolve, reject) {
  $.ajax({
   ...
   })
   .done(function(data){
      resolve(data)
   })
   .fail(function(data){
      reject(data)
   });
});

promise.then(function(result) {
  console.log(result);
}, function(err) {
  console.log(err);
});

I wonder if functionally there are differences in the two models?

3 answers

13


[...] there are [functionally] differences in the two models[?]

Fundamentally not. Promises are, at heart, callbacks; functionally the difference is that the model of Promises provides a standard way of return management of values and exceptions, as well as a flow control via handlers.

The great advantage of implementing Promises is that the return of the statement is a variable, which makes the chaining process of handlers much simpler - allowing, for example, cascade evaluations.

A post (in English) that elaborates this subject more in depth can be found at Softwareengineering.Stackexchange.

10

Promise represents a promise of a future outcome of an asynchronous operation. And Promises can be understood as asynchronous callbacks.

One of the advantages I know is using Promise.. Returns a precedent that solves when all the precedents in the iterable argument are solved.

Promise.all([chamada1(), chamada2(), ...]).then(function(resultado) {
    //Resultado é um array contém os valores das três promises
}).catch(function(error) {
    //Se ao menos uma promise for rejeitada
}); 

That is, it is possible to do n asynchronous calls and perform some operation after all are completed.

In english a discussion where they explained more advantages and characteristics.

3

A premomise is exactly what the name says, a promise. Its "promise" function that will return something, this something can be a success, error, message and etc.

What will you do with what was returned from promise is a callback. That is, a promise returns a data and the callback treats this data.

The method Ajax of jQuery that you gave as an example is an example of promise.

// função principal que retorna a promise
var ajax = $.ajax('url');

// promise retornou sucesso (resolve) então podemos tratar os dados
ajax.done(function( data ) {
    // do something awesome
})

// promise retornou erro (reject) então precisamos tratar o erro
ajax.fail(function( error ){
    // something went wrong
});

In the example you gave it is not necessary to encapsulate the Ajax in a promise because the Ajax in itself is already a promise.

See another example of promise

var preload = function( url ) {
    return new Promise(function( resolve, reject ) {
        var image = new Image();

        image.onload  = function() {
            resolve( image );
        };

        image.onerror = function() {
            reject( Error('Error while loading image: ' + url)) ;
        };

        image.src = url;
    });
};

And to use

var preloadImage = preload('image-path');

preloadImage.then(function() {
    // imagem carregou
});

preloadImage.catch(function() {
    // deu erro no carregamento
});

.then() and .catch() are the callbacks of the Promise preload

Now look at the same example as before, but now with callback.

var preload = function( url, success, error ) {
    var image = new Image();

    image.onload  = function() {
        success( image );
    };

    image.onerror = function() {
        error( Error('Error while loading image: ' + url)) ;
    };

    image.src = url;
};

And to use the callbacks it would be something like that

preload('image-path', function( image ) {
    // sucesso ao carregar a imagem
}, function( error ) {
    // deu erro ao carregar a imagem
});
  • Good guy! Thanks for the tip not to use callback or Promise in ajax. I hadn’t noticed that it was just giving a $.ajax Return on my Function a and using a.done(Function(){}). fail(Function(){}) on Function b. ;)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.