Understanding closures, callbacks and promises
#closures: a closure give you access to an outer function’s scope from an inner function outside of its original usage.
The closure has three scopes, all part of the same chain: it has access to its own scope (variables defined between its curly brackets), it has access to the outer function’s variables, and it has access to the global variables
The inner function has access not only to the outer function’s variables, but also to the outer function’s parameters.
function showName (firstName, lastName) {
var nameIntro = "Your name is ";
// this inner function has access to the outer function's variables, including the parameter
function makeFullName () {
return nameIntro + firstName + " " + lastName;
}
return makeFullName ();
}
showName ("Srikrushna", "Pal"); // Your name is Srikrushna Pal
Closures are also frequently used in jQuery and just about every piece of JavaScript code you read
#Callback: A callback is any function that is called by another function, which takes the first function as a parameter. Once the parent function completes, the function passed as an argument is then called.
//the callback function
function done(){
console.log("Done");
}
//the parent function
function increment(num, callBack){
for(var i = 0; i <= num; i++){
console.log(i);
}
return callBack();
}
//the callback function is passed to the increment function
increment(10, done);
Note: Callbacks are the standard way of handling asynchrnous code in JavaScript, but promises are the best way to handle asynchronous code. This is because callbacks make error handling difficult, and lead to ugly nested code. So we look for promise
#Promises:
Promises help you naturally handle errors and write cleaner code by not having callback parameters. A promise is in one of three different states: pending, fulfilled or rejected. promise.done allows us to wait for the promise to be fulfilled or rejected before doing something with it. The promise has a .then method which can be called with two functions, one to handle success, and the other to handle failure
A promise can be:
fulfilled – The action relating to the promise succeeded
rejected – The action relating to the promise failed
pending – Hasn’t fulfilled or rejected yet
settled – Has fulfilled or rejected
function getImage(url){
return new Promise(function(resolve, reject){
var img = new Image()
img.onload = function(){
resolve(url)
}
img.onerror = function(){
reject(url)
}
img.src = url
})
}
The getImage() function returns a Promise object that keeps track of the state of the image load. When you call getImage(‘doggy.gif’) its promise object goes from the initial state of “pending” to either fulfilled or rejected eventually depending on the outcome of the image load. Notice how we’ve passed the URL of the image to both the resolve() and reject() method of Promise;
Error handling
Whenever you instantiate a Promise object, two methods- then () and catch ()- become available to decide what happens next after the conclusion of an asynchronous task.
getImage('doggy.jpg').then(function(successurl){
document.getElementById('doggyplayground').innerHTML = '<img src="' + successurl + '" />'
})
What happens if the image failed to load? The then() method can accept a 2nd function to deal with the rejected state of the Promise object
getImage('doggy.jpg').then(
function(successurl){
document.getElementById('doggyplayground').innerHTML = '<img src="' + successurl + '" />'
},
function(errorurl){
console.log('Error loading ' + errorurl)
}
)
In such a construct, if the image loads, the first function inside then() is run, if it fails, the 2nd instead. We can also handle errors using the catch() method instead:
getImage('doggy.jpg').then(function(successurl){
document.getElementById('doggyplayground').innerHTML = '<img src="' + successurl + '" />'
}).catch(function(errorurl){
console.log('Error loading ' + errorurl)
})
Calling catch() is equivalent to calling then(undefined, function), so the above is the same as:
getImage('doggy.jpg').then(function(successurl){
document.getElementById('doggyplayground').innerHTML = '<img src="' + successurl + '" />'
}).then(undefined, function(errorurl){
console.log('Error loading ' + errorurl)
})
Related question: function/method Channing. async and sync call. Difference between callback and promise.
Short and good, you save my lots of time.
thanks for the review
Understandable and useful