Promises are a neater implementation of callbacks, back in days when we used callbacks for everything, once you do this call this function, jQuery uses the callbacks for events.
$('.testObject').click(function(){
// body goes here
})
as for Promises and how they work, in native ES6 JS all you have to do is to make a new instance of Promise object passed with a function, the function takes two arguments resolve, reject. inside the body of the function just do your magic (Call a service, make an HTTP(XHR) request). once you are done invoke resolve('content') which is a callback for a success of that promise and it is catch by .then(function(response){}), what you pass inside the resolve will be passed to the function of the then. and same goes for reject('error') and .catch(function(error){}).
Here is an example
let promise = new Promise((resolve, reject) => {
setTimeout(function(){
resolve("Success!");
}, 250);
});
myFirstPromise.then((successMessage) => {
console.log("Yay! " + successMessage);
});
What is a brilliant convention is the use of promise.all([function(){},function(){}]). where you can use this convention if you are waiting for multiple calls to be fulfilled before the .then(function(){}) to be executed. This way can save lots of written code if you used the callback.
Here is an example
//Callback example:
serviceOne.fetchData(function(){
serviceTwoPromise.fetchData();
});
//Promise example
const serviceOnePromise = function(resolve,reject){}
const serviceTwoPromise = function(resolve,reject){}
let fetchData = new Promise.all([serviceOnePromise,serviceTwoPromise]);
fetchData.then((success)=>{
}).catch((error)=>{
})
_for more information check this site: _developer.mozilla.org/en/docs/Web/JavaScript/Refe…