One word every JavaScript developer finds it common in most tutorials or documentation is 'asynchronous'.
The asynchronous concept of JavaScript becomes a bit confusing if you are a beginner. In this article, I will be showing you that the concept is not difficult as it sounds.

wow

Yes! I will discuss with you callback, promises, await and other terms related to Asynchronous JavaScript.

Synchronous vs Asynchronous

JavaScript is synchronous by default and is single threaded
This means that code cannot create new threads and run in parallel.
Lines of code are executed in series, one after another.
Let's take a look at the snippet below:

let a = 3;
let b +=a;
let c = a * b;
console.log(c);
greet();

In the snippet above, The interpreter executes these instructions one after another in that order until the last line is executed.

Asynchronous JavaScript, the code is does not get executed in series as we saw in synchronous. This means that each code gets executed independently of the main program flow.
Asynchronicity means that if JavaScript has to wait for an operation to complete, it will execute the rest of the code while waiting.

Daily Tip💡

Starting a new concept can be stressful. This becomes worse when the documentation is generic. Questions like How do I handle API operations using Async/Await?
You can do away with this stress and more using ASKYOURCODE

ASKYOURCODE


Askyourcode is one of the fast-growing codebase search engines. This site helps you to search for your desired code snippet. The result is a list of code samples fetched from GitHub. This amazing platform is free

Callbacks functions in JavaScript?

Many JavaScript activities are asynchronous, which means they don't really stop the program (or a function) from running until they're finished, as you're probably used to, which is why we require callback functions. Instead, it will run in the background whilst the other code is being executed.
A callback is a function passed as an argument to another function
This technique allows a function to call another function.
in JavaScript, functions are executed in the sequence they are called. Not in the sequence they are declared.

For instance:

function funcOne()
{
  console.log("One")
}

function funcTwo()
{
  console.log("Two")
}

funcTwo();
funcOne()

The output of the snippet about will be

Two
One

This is because funcTwo was called first before the other. A callback's primary purpose is to execute code in response to an event.
There are two types of callback, Asynchronous and Synchronous callback functions.
Sample callback snippets

const button = document.getElementById("users")
const fetchusers = async () => {
  try {
    const { data } = await Axios({
      url: "users",
      method: "GET",
    });
    console.log(data.data)
  } catch (e: any) {
    console.log(e);
  }
}


// method call
button.addEventListener("click", fetchusers)

The function fetchusers as a callback functions gets executed when the button is clicked. Note that the fetchusers is asynchronous.
Asynchronous functions return a promise, and when they run into the phrase await  (fetch() returns a promise, for example), they halt operation until the promise is fulfilled.

An asynchronous callback function differs from an asynchronous function. The higher-order function executes the asynchronous callback function in a non-blocking way. However, while waiting for promises (await ) to resolve, the asynchronous function stops its execution.

What are Promises in JavaScript?

Promises are used to handle asynchronous operations in JavaScript. They are easy to manage when dealing with multiple asynchronous operations where callbacks can create callback hell leading to unmanageable code. Callback functions were used before promises, but they had limited functionality and resulted in unmanageable code. The nightmare that would result from having several callback functions would make the code unmanageable.

A promise, in JS context, is function which will take some time to execute. There are four possible states of a promise:

  • fulfilled: Action related to the promise succeeded
  • rejected: Action related to the promise failed
  • pending: Promise is still pending i.e. not fulfilled or rejected yet
  • settled: Promise has fulfilled or rejected

A promise takes in two functions as parameters. That is, resolve and reject in declaring it.

var doSomething = new Promise(function(resolve, reject){
     let i = 3;
     let j = 5;
       if(i < j) { 
         resolve(); 
       } else { 
         reject(); 
       } 
});

Inasmuch as Promoise clears the menace caused by callback, Is it the utmost better way of handling asynchronous operations? There is a much better way. That is the Async/Await.

What is Async and Await in JavaScript?

Async/Await is the preferred way of handling data and API calls in JavaScript.

  • Async: allows you to write promises-based code as if it was synchronous. It ensures that the execution thread is not being broken. The event loop is used for its asynchronous operation. A value is always returned by async functions. It guarantees that promises be fulfilled, and if they are not, JavaScript automatically wraps them in promises that are resolved with their values.
    How is Async used?
const fetchData = async () => {
   console.log("async")
}

The async keyword is used to declare an asynchronous function.

  • Await
    Await function is used to wait for the promise. It can only be used within the async function. It makes the code wait until the promise returns a result. It only makes the async block wait.
    How is Await used?
const fetchData = async () => {
   const res = await fetch(resource)
   const data = await res.json();
   console.log(data)
}

It the snippet above, await is used to delay assignment and of the res and data variables till the promise is resolved.

Conclusion

In this article, I introduced you to the essential parts of Asynchronous JavaScript. The concepts involved was not treated in great depth.
I hope this article gives you a clear understanding and shows you that the concept is not difficult as it sounds.

Happy Hacking!

gif


Bentil here🚀
What is your experience in using Asynchronous JavaScript? I will be glad to hear from you in the comments section. If you found this article helpful, please share it with your friends and colleagues. You can also follow me here and on Twitter for more updates.

Tagged in: