DEV Community

adarsh04
adarsh04

Posted on

How to use Async/Await in place of Promises

In this post, I will teach you how to async and await in place of promises. It took me a while to grasp the concepts of async/ await, and I hope you can catch the idea in a few short minutes by reading my article :D

Promises are a way to handle asynchronous operations in the Javascript world. Whenever a long-running task is being run, the method to await the results and still carry out the other functions is to use Promises.

Let us consider a system with a long-running task (returning data from a database), and we need to print out the results to the screen.

The code below leverages Promises to achieve this.

function longRunningTask() {

  return new Promise((resolve, reject) => {
    const data = db.getAllData();
    if (data) {
      resolve(data);
    }
    reject('Error')
  });
}

longRunningTask()
  .then((data) => console.log(data))
  .catch((e) => console.log(e));
Enter fullscreen mode Exit fullscreen mode

Conceptually, I shall use the diagram below to map out different parts of the code here.

Promises

The long-running task will return a promise whose result is still pending. Once it is resolved, it will output the results.

Now, let’s leverage async/await to do the above operation.

async function longRunningTask() {
  try {
    return await db.getAllData();
  } catch(e) {
    console.log(e);
  }
}

async function currentTask() {
  try {
    const data = await longRunningTask();
    console.log(data)
  } catch(e) {
    console.log(e);
  }
}

currentTask();
Enter fullscreen mode Exit fullscreen mode

Let's depict what’s going on above with a diagram.

Async_Await

As you can see, I have removed the need to return a Promise (with resolve and reject) in the long-running task. Instead, I marked the long-running task as async and then marked the data returned from the DB with an await keyword.

Similarly, I marked the current task as async and the results returned from the long-running task with an await, rather than calling the Promise then method.

The significant advantage of using async + await is that the code is much easier to follow for someone who isn’t an expert on Promises. It tells us what is an async operation and what data we are waiting for. I’ve also found it much faster to code with async + await due to its simpler syntax.

Feel free to leave any comments in the form of feedback.

Top comments (0)