Understanding the Event Loop, Callbacks, Promises, and Async/Await in JavaScript - SkillBakery Studios

Breaking

Post Top Ad

Post Top Ad

Tuesday, October 27, 2020

Understanding the Event Loop, Callbacks, Promises, and Async/Await in JavaScript

During the initial days of the internet, the websites were mostly made up of static data on the HTML page. Whereas in the current scenario the internet applications are much more interactive and dynamic, due to which it has become necessary for developers to do intense operations for retrieving API (Application Programming Interface) data.

 

As JavaScript is a single-threaded programming language with asynchronous execution the model that processes one operation after another, it can only process one statement at a time. However, an action like requesting data from an API can take an indeterminate amount of time, depending on the size of data being requested, the speed of the network connection, and other factors.

If API calls were performed in asynchronous manner, the browser would not be able to handle any user input, like scrolling or clicking a button, until that operation completes, this is known as blocking.

In order to prevent the blocking behavior, the browser environment has many Web APIs that JavaScript can access that are asynchronous; in other-word we can say that,   they can run in parallel with other operations instead of sequentially. This is useful because it allows the user to continue using the browser normally while the asynchronous operations are being processed.

Event Loop

A web APIs will execute in a sequential manner—one at a time if JavaScript code does not use any asynchronous Web API.

When an asynchronous Web API is used, the rules become more complicated. A built-in API that you can test this with is setTimeout, which sets a timer and performs an action after a specified amount of time. setTimeout needs to be asynchronous, otherwise, the entire browser would remain frozen during the waiting, which would result in a poor user experience. 

// Define three example functions, but one of them contains asynchronous code
 function first() {
  console.log(1)
}
 function second() {
  setTimeout(() => {
    console.log(2)
  }, 0)
}
 function third() {
  console.log(3)
}

setTimeout takes two arguments- the function it will run asynchronously, and the amount of time it will wait before calling that function. In this code, you wrapped console.log in an anonymous function and passed it to setTimeout, then set the function to run after milliseconds.

 Now get the functions executed-

// Execute the functions
first()
second()
third()

should expect with a setTimeout set to 0 that running these three functions, the output will be in sequential manner, but it is asynchronous, the function with the timeout and it will be printed last and the output will be.

1

3

2

This happens because the JavaScript host environment, in this case the browser, uses a concept called the event loop to handle concurrency, or parallel events. Since JavaScript can only execute one statement at a time, it needs the event loop to be informed of when to execute which specific statement. 

Callback Functions-

In the setTimeout example, the function with the timeout ran after everything in the main top-level execution context.

But if you wanted to ensure one of the functions, like the with the timeout ran after everything in the main top-level execution context.
But if you wanted to ensure one of the functions, like the third function, ran after the timeout, then you would have to use asynchronous coding methods. The timeout here can represent an asynchronous API call that contains data.
You want to work with the data from the API call, but you have to make sure the data is returned first.timeout, then you would have to use asynchronous coding methods. The timeout
here can represent an asynchronous API call that contains data. You want to
work with the data from the API call, but you have to make sure the data is
returned first.The original solution to dealing with this problem is using callback functions. Callback functions do not have special

syntax; they are just a function that has been passed as an argument to another function. The function that takes another function as an argument is called a higher-order function. According to this definition, any function can become a callback function if it is passed as an argument. Callbacks are not asynchronous by nature, but can be used for asynchronous purposes.

Define three functions
function first() {
  console.log(1)
}
 
function second(callback) {
  setTimeout(() => {
    console.log(2)
 
    // Execute the callback function
    callback()
  }, 0)
}
 
function third() {
  console.log(3)
}

Now, execute first and second, then pass third as an argument to second:

first()

second(third)

The output will be-

1
2

3

First 1 will print, and after the timer completes (in this case, zero seconds, but you can change it to any amount) it will print 2 then 3. By passing a function as a callback, you’ve successfully delayed execution of the function until the asynchronous Web API (setTimeout) completes.

Promises

A promise represents the completion of an
asynchronous function. It is an object that might return a value in the future.
It accomplishes the same basic goal as a callback function, but with many
additional features and a more readable syntax.

A promise can have three possible states: pending, fulfilled, and rejected

  • Pending - Initial state before being resolved or rejected
  • Fulfilled - Successful operation, promise has resolved
  • Rejected - Failed operation, promise has rejected

You can initialize a promise with the new Promise syntax, and you must initialize it with a function. The function that gets passed to a promise has resolve and reject parameters. The resolve and reject functions handle the success and failure of an operation, respectively.To test out a promise is fulfill the promise by resolving it with a value:

const promise = new Promise((resolve,

reject) => {

resolve('We did it!')

})

As we can see that it has a status of fulfilled,and a value set to the value you passed to resolve:

Output

__proto__: Promise

[[PromiseStatus]]: "fulfilled"

[[PromiseValue]]: "We did it!"

In other words we can say that,promise is an object which returns a value, once it is successfully fulfilled.


AsyncFunctions with async/await-

An async function is a modification to the syntax used in writing promises. You can call it syntactic sugar over promises. Itonly makes writing promises easier.

An async function returns a promise -- if the function returns a value, the promise will be resolved with the value, but ifthe async function throws an error, the promise is rejected with that value. 

Await is only used with an async function.--The await keyword is used in an async function to ensure that all promises returned in the async function are synchronized, ie.they wait for each other. Await eliminates the use of callbacks in .then() and .catch(). In using async and await, async is prepended whenreturning a promise, await is prepended when calling a promise. try and catch are

also used to get the rejection value of an async function. 


For more such courses and topics visit our website www.skillbakery.com


No comments:

Post a Comment

Post Top Ad