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. ;)
– alan