Generator Functions in JavaScript : asynchronous behaviour of Javascript Part -3

For part 1 and part 2 of this series, see the following links https://truetocode.com/understanding-callbacks-and-callback-hell-in-javascript-asynchronous-behavior-of-javascript-part-1/697/ https://truetocode.com/understanding-promises-in-javascript-asynchronous-behavior-of-javascript-part-2/730/   JavaScript version ES6/ES2017, a new kind of function called generator functions was introduced. These special functions help you to manage asynchronous operations with more ease. Generator functions can be paused and then continued. Generator functions are declared with an asterisk (*) and have a yield keyword which yields data. See the following example to see the proper syntax for using Generator functions.

  There is a next method in the generator function prototype. To get the value of the first yield we use the next() method.

    Here you can see that the response object has a key-value which gives the value of the yield and a done key which represents the status. Here in our example,  value will be 1 and done will be false. We have two yields in the generator function .next() gives false two times and a third time gives done as true. If you add a return to the generator function next() will have key done as true.

        Now, if a return is done before a yield

Here you can see that the second yield…

Understanding Callbacks and Callback hell in JavaScript : asynchronous behaviour of Javascript Part -1

In most programming languages, functions can accept other function(s) as arguments or return a function. Such functions are called Higher-order functions. In JavaScript, most APIs and Modules can accept a function as an argument to a function. The functions are called callbacks. Structure of callbacks

Note that JavaScript functions behave as objects. We can set a function as an object property or store a function into a variable. JavaScript is a non-blocking programming language. It doesn’t wait or block operation to finish but keeps on executing. For example, consider the case when data is fetched asynchronously, then javascript doesn’t wait for the asynchronous call to get data but keeps executing the next line of code. So in order to do something with the data, we can use callbacks. See the below example in which we use a timeout to wait for the data just like an XHR request which may take some time to complete

Asynchronous callback with  Jquery and a callback function

  CALLBACK HELL Consider the above example in which we use a callback function which is passed as an argument to the $.get function in Jquery. Now what happens when we want to send subsequent requests is that…

Share this page in social media platforms