JavaScript

Asynchronous Execution in JavaScript

In many programming languages, asynchronous processes are handled by generating a new thread that operates in the background. However, in JavaScript, we have a concept called the execution context and event loop, which prevents the rest of the code from running. When the execution context discovers such code blocks in a program, it sends them back to the event loop for execution before returning them to the call stack. There are three basic types of asynchronous code methods in JavaScript programming: Callbacks, Promises, and async/await keywords.

This write-up will discuss Asynchronous Execution in JavaScript. Moreover, we will also demonstrate the JavaScript methods of executing asynchronous execution, such as Callbacks, Promises, async/await, with the help of examples. So, let’s start!

Callbacks with Asynchronous Execution in JavaScript

Callbacks are one of the most common coding styles to express and handle asynchronous execution in JavaScript. It is a type of function that needs to be called after another function has completed its execution. The callback function is invoked with the response when the specified operation gets completed. Suppose you want to ensure that a particular piece of code in your JavaScript program does not execute until the other finishes its execution. In that case, you can achieve this functionality by utilizing the callback function.

Example: Callbacks with Asynchronous Execution in JavaScript

Let us give you an example that will assist you with what we have stated. Consider a scenario in which you are required to write a string to a document stream after 7 seconds. In this case, you can use the “setTimeout()” JavaScript built-in function that evaluates an expression or calls any function after a specified amount of time. In our case, we have utilized the “setTimeout()” function to invoke the defined “myFunction()” after 7 seconds:

<!DOCTYPE html>

<html>

<body>


<p>Wait for 7 seconds (7000 milliseconds)</p>

<script>

setTimeout(myFunction,7000);

function myFunction() {

  document.write("Asynchronous Execution in JavaScript");

}

</script>


</body>

</html>

You can execute the above-given example in your favorite code editor or any online coding sandbox,; however, we will utilize the JSbin for the demonstration purpose:

After executing the provided JavaScript program, you will be asked to wait for “7 seconds”:

After 7 seconds, the string “Asynchronous Execution in JavaScript” will be shown as output:

Promises with Asynchronous Execution in JavaScript

When you chain several function calls together, one of the primary issues of the callbacks is that it becomes difficult to track the flow of the execution. The “.then()” syntax in “Promises” rescues you in such a situation while permitting you to chain promises together. It enables you to link handlers with the added asynchronous value of the success or the cause of the failure. As a result, the asynchronous methods will behave similarly to synchronous ones.

Rather than providing the final value immediately, the asynchronous technique returns a promise that offers the value that can be used in further processing. Your Promises object can be in one of the three states: pending, fulfilled, or rejected:

  • Pending: Before an operation occurs, the added Promise is in a pending state.
  • Fulfilled: The fulfilled state of a Promise signifies that the added operation has been completed.
  • Rejected: When an error value is thrown for the incomplete operation, the promise comes under the rejected state.

Example: Promises with Asynchronous Execution in JavaScript

To show the working of Promises with Asynchronous execution in JavaScript, firstly, we will define a “showMessage()” function which will be invoked for both the success and failure of the added promise:

<!DOCTYPE html>

<html>

<body>


<script>

function showMessage(text) {

  document.write(text);

}

Next, we will create a “myPromise” object, with a function having “myResolve” and “myReject” parameters. We will also add an “if” condition to check the value of the variable “a”, which will then pass the corresponding string to myResolve() or myReject():

let myPromise = new Promise(function(myResolve, myReject) {

  let a = 5;

  if (a == 5) {

    myResolve("Value is Okay");

  } else {

    myReject("Error Encountered");

  }

});

You can use the “then()” method to utilize the added promise. Our myPromise.then() method will take two arguments: a callback for success and other for the case of failure:

myPromise.then(

  function(value) {showMessage(value);},

  function(error) {showMessage(error);}

);

</script>


</body>

</html>

Execution of the above-given code will show you the following output:

Now, on purpose, we will change the value of variable “a” to check if the callback for the failure of the promise is working or not:

As you can see, the callback for the failure is displaying “Error Encountered” string according to our JavaScript program coding:

async/await with Asynchronous Execution in JavaScript

The “async” and “await” keywords are added to the more recent version of JavaScript. These keywords make writing promises easier and permit the user to have complete control over the sequence of promises execution. The async function always returns promises, and the await function is utilized in the async function to halt the execution of the added method while waiting for the promise to resolve. After that, it will resume the function’s execution and output the resolved value.

Example: async with Asynchronous Execution in JavaScript

Now, in the same example, we will add an async myFunction() which returns a promise:

<!DOCTYPE html>

<html>

<body>

<script>

function showMessage(text) {

  document.write(text);

}


async function myFunction() {return "Hi, this is linuxhint.com";}


myFunction().then(

  function(value) {showMessage(value);},

  function(error) {showMessage(error);}

);</script>


</body>

</html>

Have a look at the provided code and its output:

Example: await with Asynchronous Execution in JavaScript

In this example, we will first add the “async” keyword with the showMessage() function definition to output a promise. After doing so, we will specify “await” with the created “myPromise” object so that it will wait for the myPromise:

<!DOCTYPE html>

<html>

<body>


<script>

async function showMessage() {

  let myPromise = new Promise(function(resolve, reject) {

    resolve("Hi, this is linuxhint.com");

  });

  document.write(await myPromise);

}


showMessage();

</script>


</body>

</html>

Here is the output we got from executing the above-given example:

Conclusion

Callbacks, Promises, and async/await keywords are the three methods for handling asynchronous execution in JavaScript. Callbacks enable access to the functions when the asynchronous method has completed the execution; Promises assist in chaining the method together, and the async/await keyword provides additional control over the promises. This write-up discussed Asynchronous Execution in JavaScript. Moreover, we also demonstrated the methods of asynchronous execution such as Callbacks, Promises, async/await in JavaScript with examples.

About the author

Sharqa Hameed

I am a Linux enthusiast, I love to read Every Linux blog on the internet. I hold masters degree in computer science and am passionate about learning and teaching.