Skip to content

Instantly share code, notes, and snippets.

@ShawonAshraf
Forked from amysimmons/js-tricky-bits.md
Created June 22, 2018 07:32
Show Gist options
  • Save ShawonAshraf/18badce4138cd7a8350f98bc4591a19d to your computer and use it in GitHub Desktop.
Save ShawonAshraf/18badce4138cd7a8350f98bc4591a19d to your computer and use it in GitHub Desktop.
Understanding closures, callbacks and promises in JavaScript

#Understanding closures, callbacks and promises

For a code newbie like myself, callbacks, closures and promises are scary JavaScript concepts.

10 months into my full-time dev career, and I would struggle to explain these words to a peer.

So I decided it was time to face my fears, and try to get my head around each concept.

Here are the notes from my initial reading. I'll continue to refine them as my understanding improves.

I hope they help!

Cheers,

Amy

##Closures

Source: How do JavaScript Closures Work

  • In JavaScript, if you use the function keyword inside another function, you are creating a closure
  • A regular function created in the global scope can also close over variables
  • The below code has a closure because the anonymous function function() { console.log(text); } is declared inside another function, sayHello2()
function sayHello2(name) {
    var text = 'Hello ' + name; // Local variable
    var say = function() { console.log(text); }
    return say;
}
var say2 = sayHello2('Bob');
say2(); // logs "Hello Bob"
  • If you declare a function within another function, then the local variables can remain accessible after returning from the function you called
  • This is demonstrated above, because we call the function say2() after we have returned from sayHello2(). The code that we call is still able to reference the variable 'text', which was a local variable of the function sayHello2()

Source: Understanding JavaScript Closures With Ease

  • A closure is an inner function that has access to the outer (enclosing) function's variables
  • 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 ("Amy", "Simmons"); // Your name is Amy Simmons

My own attempt: Also on JS Fiddle

//this example uses a closure because:
//a function is defined inside another function
//the inner function has access to the outer functions variables, 'text'
//the outer function's variables can be accessed even after the outer function is called

function surpriseMe(surprise){
	var text = "Today you will be surprised with " + surprise;
  
  function revealSurprise(){
  	alert(text);
  }
  
  return revealSurprise;
}

var surprise = surpriseMe("1000 puppy dogs");
surprise();

##Callbacks

Source: JavaScript The Good Parts

  • Take the following example: a user interaction triggers a request to a server, and the response from the server should be displayed in the browser
  • A synchronous way of doing this would be:
//synchronous example:

request = prepare_the_request();
response = send_request_synchronously(request);
display(response)
  • Because the above code is synchronous, the program will wait for it to finish before moving on to another task
  • If either the network or the server is slow, the user will be left waiting
  • A better way of doing this would be with an asynchronous request, which provides a 'callback' function which will be invoked once the server's response is received:
//asynchronous example:

request = prepare_the_request();
response = send_request_asynchronously(request, function (response) {
	display(response);
});
  • When you execute something asynchronously, the program can move on to another task before the request finishes

Source: What is a callback function?

A callback function is a function which is:

  • passed as an argument to another function
  • is invoked after some kind of event
  • once its parent function completes, the function passed as an argument is then called

Source: How to explain callbacks in plain english?

  • A callback is any function that is called by another function, which takes the first function as a parameter
  • Consider how programmers normally write to a file:
fileObject = open(file)
//now that we have WAITED for the file to open, we can write to it

fileObject.write("We are writing to the file.")
//now we can continue doing the other, totally unrelated things our program does
  • In the above example, we wait for the file to open, before we write to it.
  • This blocks the flow of execution, and our program cannot do any of the other things it might need to do
  • This is where callbacks are useful:
//we pass writeToFile (a callback function) to the open function
fileObject = open(file, writeToFile)

//execution continues flowing -- we don't wait for the file to be opened
//once the file is opened we write to it, but while we wait we can do other things

My own attempt: Also on JS Fiddle

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

##Promises

Source: Udacity JavaScript Promises

  • Normally code is synchronous - one statement executes and there is a guarantee that the next statement will execute immediately afterwards
  • With asynchronous operations, you should assume that you have no idea when the operation will complete. You can't even assume that just because you send out one request first, and another request second, that they will return in that order
  • 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.

Source: Promisejs.org

  • Promises help you naturally handle errors, and write cleaner code by not having callback parameters
  • A promise represents the result of an asynchronous operation. A promise is in one of three different states: pending, fulfilled or rejected
  • Once a promise is fulfilled or rejected, it is immutable (i.e. it can never change again)
  • We use new Promise to construct the promise, the constructor is called immediately with two arguments - one that fulfils the promise and the other that rejects the promise
  • promise.done allows us to wait for the promise to be fulfilled or rejected before doing something with it

Source: JavaScript Promise API

Basic usage:

var p = new Promise(function(resolve, reject) {
	
	// Do an async task async task and then...

	if(/* good condition */) {
		resolve('Success!');
	}
	else {
		reject('Failure!');
	}
});

p.then(function() { 
	/* do something with the result */
}).catch(function() {
	/* error :( */
})

Realistic example:

  • A realistic example of using promises would be converting a get request to a promise-based task:
// From Jake Archibald's Promises and Back:
// http://www.html5rocks.com/en/tutorials/es6/promises/#toc-promisifying-xmlhttprequest

function get(url) {
  // Return a new promise.
  return new Promise(function(resolve, reject) {
    // Do the usual XHR stuff
    var req = new XMLHttpRequest();
    req.open('GET', url);

    req.onload = function() {
      // This is called even on 404 etc
      // so check the status
      if (req.status == 200) {
        // Resolve the promise with the response text
        resolve(req.response);
      }
      else {
        // Otherwise reject with the status text
        // which will hopefully be a meaningful error
        reject(Error(req.statusText));
      }
    };

    // Handle network errors
    req.onerror = function() {
      reject(Error("Network Error"));
    };

    // Make the request
    req.send();
  });
}

// Use it!
get('story.json').then(function(response) {
  console.log("Success!", response);
}, function(error) {
  console.error("Failed!", error);
});

Source: Eloquent JavaScript

  • Promises wrap an asynchronous action in an object, which can be passed around and told to do certain things when the action finishes or fails
  • Simialr to the above example:
funciton get(url){
	return new Promise(function(succeed, fail){
		var req = new XMLHttpRequest();
		req.open("GET", url, true);
		req.addEventListener("load", function(){
			if(req.status < 400){
				succeed(req.responseText);
			}else{
				fail(new Error("Request failed: " + req.statusText));
			}
		});
		req.addEventListener("error", function(){
			fail(new Error("Network error"));
		});
		req.send(null);
	});
}
  • The get function above receives a url, and returns a promise
  • The promise has a .then method which can be called with two functions, one to handle success, and the other to handle failure
get("example/data.txt").then(function(text){
	console.log("data.txt: " + text);
}, function(error){
	console.log('Failed to fetch data.txt: " + error);
});
  • Calling .then produces a new promise, whose result depends on the return value of the first function we passed to then

My JS Fidles:

##Tasks to help my understanding of closures, callbacks and promises:

  1. Log the numbers 1 to 10 in the console with one second intervals using a loop: https://jsfiddle.net/4kdua72m/2/
for (var i = 0; i <= 10; i++) {
   (function(index) {
       setTimeout(function(){
       	console.log(index);
       }, 1000 * index);
   })(i);
}

//the above uses an IIFE, an immediately invoked function expression 
//the IIFE takes in its own private copy of i
//it console logs the index at 1000ms, 2000ms, 3000ms, etc
//IIFE is the quickest way of creating a closure 
  1. Log the numbers 1 to 10 in the console with one second intervals without using a loop: https://jsfiddle.net/v9qybf6x/2/
var i = 0;

function loop(){
   setTimeout(function(){
      console.log(i);
      i++;
      if (i <= 10){
      	loop();
      }
    }, 1000)
}

loop()

##Additional sources

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment