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