Skip to main content

Command Palette

Search for a command to run...

Async/Await in JavaScript.

Writing Cleaner Asynchronous code.

Updated
•6 min read•View as Markdown
Async/Await in JavaScript.

Why async/await introduced.

So let me explain. We start with the problem statement.

  • The problem statement is that we were using synchronous code. Synchronous code runs sequentially, line by line.

  • Now suppose we have 3–4 functions in a file, and those functions take too much time to execute. For example, they are calling an API and it takes more than one minute.

  • So what happens is, that one minute is spent on the API call. Because of this, the rest of the code gets blocked. The next statements will not execute until that function finishes execution.

  • This is called blocking, and it is a big problem in computer science because even one second delay can be problematic.

  • To solve this problem, asynchronous code was introduced. Basically, async code runs concurrently, which means it is non-blocking. It does not block other code execution.

  • Now the problem statement is clear. To implement this, async and await keywords were introduced. Basically, they work with promises.

  • Async means an asynchronous function, and it always returns a promise.

  • Await works with the state of a promise, like resolved or rejected.

So now we understand why this was introduced. In the next section, we will see this step by step in more detail.

How async function work.

  • When you declare a function using async, it means you have made that code asynchronous. Now it will not block the main thread and can run in parallel.

  • Async also makes the code promise-based. This means it always returns a promise. Even if you return a normal (non-promise) value, it automatically wraps it inside a resolved promise.

  • Because of this, you don't need to write full promise-based code every time. We will discuss this later, like why we use async and await instead of writing promises manually.

  • So overall, you are just telling JavaScript that this is asynchronous code by using the async keyword.

Await keyword concept.

  • First, you can use the await keyword only when your function is declared as async. If the function is not async, it will throw an error.

  • This is because await waits for a promise to be either resolved or rejected. So obviously, it works only when your code is dealing with a promise. If there is no promise, then there is nothing to resolve or reject.

  • You should use await when you are fetching data from an API, because it ensures that the promise is resolved before moving forward.

  • Again, await can only be used inside an async function.

Error Handling with async code.

We can handle errors in async code by using try and catch. Basically, we declare an async function, and inside it we use a try-catch block.

  • In the try block, we write our logic. If the code runs correctly, the try block will execute successfully.

  • If even one line throws an error, then the control goes to the catch block, and the error is returned from there.

  • So whatever business logic we write, it will be inside the try block. For example, when we make an API call, we use await because it gives us promise that the call is handled as a promise, it will either resolve or reject.

  • When the data comes, we return it. If something goes wrong, the error is handled in the catch block.

So this is how we handle errors in async code.

  • Once again, using the async keyword makes the function asynchronous. Inside it, we use a try-catch block for error handling. The try block contains our logic, and by using await, we trust that it is a promise and will return some result.

  • In the try block, we write our logic. If the code runs correctly, the try block will execute successfully.

    If even one line throws an error, then the control goes to the catch block, and the error is returned from there.

    So whatever business logic we write, it will be inside the try block. For example, when we make an API call, we use await because it gives us confidence that the call is handled as a promise — it will either resolve or reject.

    When the data comes, we return it. If something goes wrong, the error is handled in the catch block.

    So this is how we handle errors in async code.

    Once again, using the async keyword makes the function asynchronous. Inside it, we use a try-catch block for error handling. The try block contains our logic, and by using await, we trust that it is a promise and will return some result.

    So this is how error handling works in async code.

  • So below is a simple code on error handling with async function, then you will understand it actually.

async function user(){
 try {
   const result = await fetch("you request api url");
   
   if(!result){
     throw new Error("Failed to get data");
   }

   const data = await result.json();
   console.log(data);
} catch (error) {
    console.log("Error", error.message);
 }
};

user();

Comparison with promises.

It is not like we can write asynchronous code only using async and await. We can also write it using simple promises.

  • Now let's see a comparison of why we use async/await instead of promises.

  • If we write code using simple promises, the code can become messy. First, we declare a promise, then pass resolve and reject as parameters. After that, we use promise chaining with .then(), and keep passing data from one function to another for each operation.

  • But with async/await, it becomes simple. We just use the async keyword to declare the function as asynchronous. Instead of promise chaining, we use await to handle the promise state.

  • If we want to handle errors, we can simply use try-catch, as we saw earlier.

  • So this is the basic comparison between the two.

💡
So with my above explanation i hope you understand what i learn and what's my thought process on Async/Await in JavaScript.