Difference between promise and callback

12

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

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

With Promise, it would look 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 would like to know if functionally there are differences in the two models?

    
asked by anonymous 30.11.2016 / 19:40

3 answers

11
  

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

Fundamentally not. Promises are, in the background, callbacks ; functionally the difference is that the promises model provides a standard way of returning values and exceptions management, 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 handler chaining process much simpler - allowing, for example, cascading evaluations.

A post that elaborates on this subject further can be found in SoftwareEngineering.StackExchange .

    
30.11.2016 / 19:59
8

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 when using Promise.all . Returns a promise that resolves when all promises in the iterable argument are resolved.

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

In other words, it is possible to do asynchronous calls and perform some operation after all are completed.

In English a discussion where they explained more advantages and features.

    
30.11.2016 / 20:00
4

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

What you're going to do with what was returned from promise is callback . That is, a promise returns a data and callback treats that data.

The Ajax of jQuery method 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 you do not need to encapsulate Ajax into promise because Ajax itself is already 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 promise preload

Now see the same example above, 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 callbacks would be something like this

preload('image-path', function( image ) {
    // sucesso ao carregar a imagem
}, function( error ) {
    // deu erro ao carregar a imagem
});
    
30.11.2016 / 20:11