Asynchronous JavaScript | Callbacks | Closures



In this article, we are going to discuss Asynchronous tasks in significant depth. We will be discussing what exactly are Asynchronous tasks, what the hack are callbacks, closures, promises and much more in the context of JavaScript.

Overview: What exactly is Performing Tasks Asynchronously?

As Google says, Asynchronous is what not existing or occurring at the same time.When we execute something synchronously we start some sort of task like fetching a weather report from some 3rd party server and then we have to wait for it to finish before we move on to the next thing. When we execute something asynchronously we can start some task then we can actually get other work done before the task completes, and that’s the beauty of performing tasks asynchronously.

Callbacks in JavaScript:

Callbacks are simply Functions In JavaScript which are to be called and then executed after the execution of another function has finished. So how it happens? Actually, In JavaScript, functions are itself considered as objects and hence as all other objects, even functions can be sent as arguments to other functions. The most common and generic use case one can think of is setTimeout() function in JavaScript.

Consider the following Example of setTimeout() in JavaScript and hence try to get hands-on Callbacks JavaScript gave to us by default.

//with customary function signature  
setTimeout(function() {  
  console.log('hello1');  
}, 1000);  

//with arrow function signature  
setTimeout(() => {  
  console.log('hello2');  
}, 2000);  
        

In the above example, I have used setTimeout() function by passing a callback function as an argument into it along with the second argument which is simply the no of milliseconds after which our callback function would get executed. I have shown two ways of passing a callback function here, one is the more of customary approach and the second one is with arrow function approach which is a bit modern way.

Hitting HTTP Requests in Javascript:

Suppose, I want to hit an HTTP Request to an API which fetches a random text for me. We won’t be digging much into details of hitting HTTP Requests as this is out of the scope of this article.

Now, to hit that API, you need to create two files:

index.html

   
   
     
     
       
     
   
        

app.js

 const puzzleAPIhit = () => {  
   const request = new XMLHttpRequest()  
   request.addEventListener('readystatechange', (e) => {  
     if (e.target.readyState === 4 && e.target.status === 200) {  
       const data = JSON.parse(e.target.responseText);  
       console.log(data.puzzle)  
     } else if (e.target.readyState === 4) {  
       console.log('An error has taken place')  
     }  
   })  
   request.open('GET', 'http://puzzle.mead.io/puzzle?wordCount=3')  
   request.send()  
 }  
 puzzleAPIhit(); 
        

Now, when you open the “index.html” file in your browser, you can see a random string getting printed in the console.

Callback Abstraction:

Now, what if we have a complex application or something like an entire game is built over this and hence the logic of generation of a random string is something which we should keep hidden or abstract from “users”. To understand this, we can create three files:

index.html

   
   
     
       
       
     
  
      

makerequest.js

 const puzzleAPIhit = () => {  
   return 'some random string';  
 }  
      

app.js

 const myPuzzle = puzzleAPIhit();  
 console.log(myPuzzle);  
      

Now, we need to replace the actual logic of finding the random string with the hardcoded return statement in puzzleAPIhit() function. But as the hitting of an HTTP request is asynchronous nature, we can’t simply do this: (changing contents of makerequest.js and keeping rest two files intact)

makerequest.js

 const puzzleAPIhit = () => {  
   const request = new XMLHttpRequest()  
   request.addEventListener('readystatechange', (e) => {  
     if (e.target.readyState === 4 && e.target.status === 200) {  
       const data = JSON.parse(e.target.responseText);  
       console.log(data.puzzle)  
       return data.puzzle;   
       /*  
         This is absolutely impossible the request.open() is   
         asynchronous in nature.  
       */  
     } else if (e.target.readyState === 4) {  
       console.log('An error has taken place')  
     }  
   })  
   request.open('GET', 'http://puzzle.mead.io/puzzle?wordCount=3')  
   request.send()  
 }    

Because in the console, it would be printing:

 undefined  
 Reliable Public Transportation //A random string  
    

It is happening because, as the request.open() is asynchronous in nature, inside app.js, this is what happens:

  • “puzzleAPIhit()” starts its execution but being asynchronous, it would move to the next statement while parallelly running the HTTP request.
  • “console.log(myPuzzle);” gets executed even before the execution of “puzzleAPIhit()” is completed and hence prints undefined.

Solution? use callbacks. Here’s what we can do:

app.js

 const myPuzzle = puzzleAPIhit((error, puzzle) => {  
   if(error) {  
     console.log(`Error: ${error}`)  
   } else {  
     console.log(puzzle)  
   }  
 });  
    

makerequest.js

 const puzzleAPIhit = (callback) => {  
   const request = new XMLHttpRequest()  
   request.addEventListener('readystatechange', (e) => {  
     if (e.target.readyState === 4 && e.target.status === 200) {  
       const data = JSON.parse(e.target.responseText)  
       callback(undefined, data.puzzle)  
     } else if (e.target.readyState === 4) {  
       callback('An error has taken place', undefined)  
     }  
   })  
   request.open('GET', 'http://puzzle.mead.io/puzzle?wordCount=3')  
   request.send()  
 }  
    

index.html (no change)

What we have done? We have just replaced the synchronous call to asynchronous one by sending the callback in puzzleAPIhit() as an argument. And in the method puzzleAPIhit() itself, we called the callback after we have got our results which validates the basic definition of callbacks.

Closures:

A Closure is nothing but a function that has access to the variables defined in outer (and enclosing) function. As far as scope is concerned, the closure has access to global variables, its own variables, and variables of outer (and enclosing) function.

Consider the two simple examples of Closure:

 //////////////////////////Example 1://////////////////////////  
 const myFunction = () => {  
   const message = 'My New Message';  
   const printMessage = () => {  Consider the two simple examples of Closure:
     console.log(message);  
   }  
   printMessage();  
 }  
 myFunction();  
 //////////////////////////Example 2://////////////////////////  
 const myFunctionTwo = () => {  
   const message = 'My New Message Two';  
   const printMessage = () => {  
     console.log(message);  
   }  
   return printMessage;  
 }  
 const myPrintMessage = myFunctionTwo();  
 myPrintMessage();  
      

It produces the following output:

 My New Message  
 My New Message Two  
      

From Example two, one can see, the closure has access to the variable (i.e, “message”) even after the function myFunctionTwo() completed its execution, and that’s the great advantage of using closures.

Method Currying:

When a function, instead of taking all the arguments at once, takes only one argument and returns a function which will then take the rest of the arguments, this process is known as Method Currying.

For Example:

 /*  
   We have a function adderFunction which returns another function.  
   That return function in turn returns the sum.  
  */  
 const adderFunction = (a) => {  
   return (b) => {  
     return a + b;  
   }  
 }  
 const addToTen = adderFunction(10);  
 console.log(addToTen(12));  
 console.log(addToTen(-1));  
 const addToThousand = adderFunction(1000);  
 console.log(addToTen(18));  
 console.log(addToTen(121));  
          

Which Produces the following output:

As can be easily seen, now we don’t have to call the function each time with all its arguments, i.e, Method Currying helps in avoiding the need of passing a variable again and again. It also facilitates the reuse of our code.

Promises:

Promises are nothing but a much more improvised approach of handling and structuring asynchronous code in comparison to doing the same with callbacks. To prove this we are going to compare and contrast Promises with Callbacks within the same code snippet. To simulate the delay, instead of calling a third-party API, we would be using the setTimeout() method just to make things a little simpler.

The Promise receives two Callbacks in constructor function: resolve and reject. These callbacks inside promises provide us with fine-grained control over error handling and success cases. The resolve callback is used when the execution of promise performed successfully and the reject callback is used to handle the error cases.
When calling the promise, we have then method defined over promise object which can be used to receive the data from promises accordingly.

Consider the following Code Snippet:

 //Example of Callback  
 const getDataCallback = (callback) => {  
   setTimeout(() => {  
     const temp = Math.floor(Math.random()*10 + 1);//Generates a random value [1, 10]  
     (temp <= 5)   
       ? callback(undefined, 'This is the Callback data')   
       : callback('This is the Callback error', undefined);    
   }, 10);  
 };  
 getDataCallback((error, data) => {  
   if(error) {  
     console.log(error);  
   } else {  
     console.log(data);  
   }  
 });  
 //Example of Promise  
 const myPromise = new Promise((resolve, reject) => {  
   setTimeout(() => {  
     const temp = Math.floor(Math.random()*10 + 1);//Generates a random value [1, 10]  
     (temp <= 5)   
       ? resolve('This is the Promise data')   
       : reject('This is the Promise error');    
   }, 10);  
 });  
 myPromise.then((data) => {  
   console.log(data);  
 }, (error) => {  
   console.log(error);  
 });  
      

It produces the following output:

 This is the Callback data  
 This is the Promise error  
      

Short-Hand Syntax for Promises:

Suppose we have a function which accepts some integer and returns a promise based on some complex calculations (which, however, we will be simulating with setTimeout()). Actually, there is nothing special in Short-Hand Syntax except it provides a concise way of returning objects, variables or even promises from functions (functions using arrow syntax).

Consider the following Code Snippet:

 //Example of a function returning a Promise  
 const getDataFromPromise = (data) => {  
   return new Promise((resolve, reject) => {  
     setTimeout(() => {  
       (data <= 5)   
         ? resolve('This is the Promise data')   
         : reject('This is the Promise error');    
     }, 1000);  
   });  
 }    
 //Example of a function returning a Promise using Short-Hand syntax  
 const getDataFromPromiseUsingShortHandSyntax = (data) => new Promise((resolve, reject) => {  
   setTimeout(() => {  
     (data <= 5)   
       ? resolve('This is the Promise data using Short-Hand syntax')   
       : reject('This is the Promise error using Short-Hand syntax');    
   }, 1000);  
 });  
 const myPromiseOne = getDataFromPromise(3);  
 myPromiseOne.then((data) => {  
   console.log(data);  
 }, (error) => {  
   console.log(error);  
 });  
 const myPromiseTwo = getDataFromPromiseUsingShortHandSyntax(30);  
 myPromiseTwo.then((data) => {  
   console.log(data);  
 }, (error) => {  
   console.log(error);  
 });  
        

It produces the following output:

 This is the Promise data  
 This is the Promise error using Short-Hand syntax  
        

Promise Chaining:

Suppose we have a function funcA(). Suppose, funcA() returns a number after multiplying the input number with 2 if the input type is number otherwise return an error. And based on the output received from funcA(), we again want to call the same function (i.e, functA()) by passing the output received from the first call as an input.

As we did before, While solving the problem above, we would be contrasting and comparing the Callback approach and Promise approach.

Consider the following Code Snippet(Callback Approach):

 //Callback Approach  
 const funcA = (num, callback) => {  
   setTimeout(() => {  
     if(typeof num === 'number') {  
       callback(undefined, 2*num);  
     } else {  
       callback('Input type must be number');  
     }  
   }, 2000);  
 }  
 funcA(2, (error, data) => {  
   if(error) {  
     console.log(error);  
   } else {  
     funcA(data, (error, data) => {  
       if(error) {  
         console.log(error);  
       } else {  
         console.log('Final Output(Using Callback Approach): ' + data);  
       }  
     });  
   }  
 });  
        

As one can easily see and analyze, it is getting messier as it grows. So what we’re seeing here is commonly called Callback hell. Yes, there is actually a name for this messier code and obviously, we need a better solution which is both manageable and understandable and Promise Chaining comes to our rescue here.
However, With Promises, We would be seeing two approaches here:

Consider the following Code Snippet(Promise Approach, without Promise Chaining):

 const funcA = (num) => new Promise((resolve, reject) => {  
   setTimeout(() => {  
     (typeof num === 'number')   
       ? resolve(2*num)   
       : reject('Input type must be number');  
   }, 2000);  
 });  
 funcA(2).then((data) => {  
   funcA(data).then((data) => {  
     console.log(data);  
   }, (error) => {  
     console.log(error);  
   });  
 }, (error) => {  
   console.log(error);  
 });  
        

Even without Promise Chaining, our code looks far leaner with simple Promise Approach as compared to bare Callback approach. Now, we would be looking a still better approach which uses Promise Chaining. Before moving to the code of Promise Chaining, let us put some light on it theoretically:

  1. When we return a Promise from another Promise handler (i.e, then()), it is called Promise Chaining.
  2. We can easily attach another then() handler when our Promise resolves (the one we have returned) and this can be done n number of times based on our needs.
  3. We can employ a single error handler called catch() which is attached at the very last of our Promise Chaining.

Consider the following Code Snippet(Promise Approach, with Promise Chaining):

 const funcA = (num) => new Promise((resolve, reject) => {  
   setTimeout(() => {  
     (typeof num === 'number')   
       ? resolve(12*num)   
       : reject('Input type must be number');  
   }, 2);  
 });  
 funcA(12).then((data) => {  
   return funcA(data);  
 }).then((data) => {  
   console.log(data);  
 }).catch((error) => {  
   console.log(error);  
 });  
          

As one can see, the code is much much cleaner and concise now, thanks to Promise Chaining.

Fetch API:

The Fetch API introduced in relatively newer versions of JavaScript and has built-in support for Promises. Technically, it is just another method of hitting HTTP Requests while harnessing the powers and perks of Promises and Promise Chaining. Previously, we have seen how we can hit the HTTP Requests in this article.

So in the fetch API, you pass the arguments in the following order:

  • URL
  • {} (This is purely optional, used to customize our Request)

The fetch API simply returns a Promise and hence we can implement handlers like then to process the response from the promise. Based on the promise resolves or rejects, we can handle that in then().

Consider the following Code Snippet:

 fetch('http://puzzle.mead.io/puzzle', {}).then((response) => {  
   if (response.ok) {  
     return response.json();  
     /*  
       Actually, the .json() method takes the response and returns a Promise Object and hence  
       We need to add another then() as we have done in Promise Chaining   
     */  
   } else {  
     throw new Error('Unable to fetch the puzzle');  
   }  
 }).then((data) => {  
   console.log(data.puzzle);  
 }).catch((error) => {  
   console.log(error);  
 });  
         

Async-Await:

We have the async function and the Awake operator. When we use them together we get a new way to structure and work with our promises that makes the code a whole lot easier to work with. So, what Async and Await do? Let’s start with Async:

Consider the following Code Snippet:

 const processData = () => {  
   return 12;  
 };  
 const processDataAsycn = async () => {  
   return 12;  
 };  
 console.log('Data from processData() without async: ' + processData() );  
 console.log('Data from processDataAsycn() with async: ' + processDataAsycn() );  
          

It produces the following output:

 Data from processData() without async: 12  
 Data from processDataAsycn() with async: [object Promise]  
          

As you can see, adding async keyword to a function makes it work a bit differently. It starts returning a promise. The promise we get back from an async function gets resolved with whatever value we return from that function. As with any function returning promises, we can handle the response (i.e, promise) from an async function using handlers like catch and then.

Consider the following Code Snippet:

 const processDataAsycn = async (num) => {  
   if(typeof num === 'number') {  
     return 2*num;  
   } else {  
     throw new Error('Something went wrong');  
   }  
 };  
 processDataAsycn(21).then((data) => {  
   console.log('Data from processDataAsycn() with async( When promise gets resolved ): ' + data);  
 }).catch((error) => {  
   console.log('Error from processDataAsycn() with async( When promise gets rejected ): ' + error);  
 });  
          

Now, moving to await operator, let us suppose we have an async function processData() which calls a function getDataPromise() which in turn returns a promise. Now, we want to parse/use the data returned. Let us see, how we would solve the problem without await operator.

Consider the following Code Snippet:

 const getDataPromise = (num) => new Promise((resolve, reject) => {  
   setTimeout(() => {  
     (typeof num === 'number') ? resolve(num * 2) : reject('Input must be an number');  
   }, 2000);  
 });  
 const processDataAsycn = async () => {  
   return getDataPromise(22).then((data) => {  
     return getDataPromise(data);  
   });  
 };  
 processDataAsycn().then((data) => {  
   console.log('Data from processDataAsycn() with async( When promise gets resolved ): ' + data);  
 }).catch((error) => {  
   console.log('Error from processDataAsycn() with async( When promise gets rejected ): ' + error);  
 });   
          

Now, we would be implementing the same logic with the await keyword so that we can compare and contrast the two methods. Actually, The keyword await makes JavaScript wait until that promise settles and returns its result. So, it looks like the code is synchronous but it is indeed Asynchronous.

Consider the following Code Snippet:

 const getDataPromise = (num) => new Promise((resolve, reject) => {  
   setTimeout(() => {  
     (typeof num === 'number') ? resolve(num * 2) : reject('Input must be an number');  
   }, 2000);  
 });  
 const processDataAsycn = async () => {  
   let data = await getDataPromise(2);  
   data = await getDataPromise(data);  
   return data;  
 };  
 processDataAsycn().then((data) => {  
   console.log('Data from processDataAsycn() with async( When promise gets resolved ): ' + data);  
 }).catch((error) => {  
   console.log('Error from processDataAsycn() with async( When promise gets rejected ): ' + error);  
 });   
                

So with async and the awake operator, we can structure our code that uses promises to look more like regular old synchronous code. We can perform one operation after the other. This other code is never going to run until the previous promise either resolves or rejects the return statement.

Now, in this case, we’ve only seen the happy path where all of the promises do indeed resolve. Let’s go ahead and explore what happens when one of them rejects

Consider the following Code Snippet:

 const getDataPromise = (num) => new Promise((resolve, reject) => {  
   setTimeout(() => {  
     (typeof num === 'number') ? resolve(num * 2) : reject('Input must be an number');  
   }, 2000);  
 });  
 const processDataAsycn = async () => {  
   let data = await getDataPromise('2');  
   data = await getDataPromise(data);  
   return data;  
 };  
 processDataAsycn().then((data) => {  
   console.log('Data from processDataAsycn() with async( When promise gets resolved ): ' + data);  
 }).catch((error) => {  
   console.log('Error from processDataAsycn() with async( When promise gets rejected ): ' + error);  
 });   
              

It produces the following output:

 Error from processDataAsycn() with async( When promise gets rejected ): Input must be an number

The awake operator throws the error for us if the promise is rejected. We can see that promise chaining is no longer a daunting thing.




Source link

https://www.sharethelinks.com/2019/02/20/asynchronous-javascript-callbacks-closures/

Comments

Popular posts from this blog

لماذا يحتاج الذكاء الاصطناعي دائمًا إلى الرقابة البشرية ، لا يهم مدى ذكائه

70 في المائة من جميع مجالات الويب فشل في التجديد بعد عام واحد من الشراء

Reminder: StackSkills Unlimited Lifetime Access for $59