Javascript Async/Await Simplified

A simple explanation of Javascript Async/Await for those who find it complex

For a long time, I’ve been confused about Async/Await syntax in JavaScript. I’d heard that these keywords were just syntactical sugar on top of Promises, but I didn’t know how exactly they worked. Well, I finally get it now, and it’s a lot simpler than I thought!

Promises

Promises on their own already help greatly with writing asynchronous code. Pass in a function to a new promise, then call .then() on the promise with a callback to execute once the function is done.

Here’s a short example of how a promise might be used in some code:

function work() {
  // instead of a timeout, other work could be done
  // such as sending a request to a server
  return new Promise(() => setTimeout(resolve, 1000));
}

// the work function returns a promise!
work().then(() => alert("The work is done!"));

This works well, but what if things get a little more complex? Say we need to do some additional work inside of the work function that may also take some time. We could write this with promises as well!

function taskA() {
  return new Promise(resolve_taskA => setTimeout(resolve_taskA, 750));
}

function taskB() {
  return new Promise(resolve_taskB => setTimeout(resolve_taskB, 250));
}

function work() {
  return new Promise(resolve_work => {
    taskA().then(() => taskB().then(resolve_work));
  });
}

work().then(() => alert("The work is done!"));

This code works perfectly fine. However, it isn’t that maintainable. What if there were 50 tasks that we had to do in order inside the work function? We certainly wouldn’t want to have 50 layers of nested promises like this. Plus, even if we did ever figure out the right number of closing parentheses, no one else would be able to look at it and say with certainty what’s going on. It’s not readable.

Async/Await

This is where the heroes come in to save the day! Async and Await are used in scenarios like this to save time and space. Just remember that Promises are always right under the hood.

The async keyword modifies a function to make it return a promise that resolves itself when the contents of the function return.

The await keyword, when used inside an asynchronous function, forces the code to pause until the following promise fulfills.

We’ll look more closely at each keyword and smaller examples of each one, and then we’ll implement Async and Await together into our example above.

Async

The async keyword is used in front of a function declaration. When a function is asynchronous, it executes outside the main thread. It can be called from anywhere, just like a normal function can be.

async function sendMessage() {
  // lots of code that takes a long time (no callbacks, yet)
  return;
}

console.time("message");
sendMessage();
console.endTime("message"); // basically 0.0 ms

When it is called, it runs asynchronously, not interrupting the flow of other code. This seems really cool and unique, but under the hood, it’s really the same thing as a Promise.

Instead of executing its contents in order before returning to its calling context, it returns a promise that is fulfilled as soon as the function returns. The way to write an async function using promises, instead, would be to call the regular function inside a new promise like so:

function sendMessage() {
  // lots of code that takes a long time (no callbacks, yet)
  return;
}

new Promise(resolve => {
  sendMessage();
  resolve();
}

This works because the contents of a promise are executed as soon as the promise is created.

So, a function with async in front of it simply returns a promise of itself, which is resolved whenever the function returns. Using async, we can simply use .then() after calling the function:

async function sendMessage() {
  // lots of code that takes a long time (no callbacks, yet)
  return;
}

const justAnotherPromise = sendMessage();
justAnotherPromise.then(() => alert("The message has been sent"));

Await

await is a keyword that can be used to run asynchronous code synchronously. When a promise is placed directly after this keyword, code execution is paused until the promise resolves.

It’s important to note that this behavior is limited to use within asynchronous functions, so the main thread can’t be paused in this way.

async function sendMessage() {
  const longPromise = new Promise(resolve => setTimeout(resolve, 1000));
  await longPromise;
  return;
}

sendMessage().then(() => alert("The message has been sent"));

Because we used the await keyword in front of a promise inside an async function, the code will stop until longPromise completes, after the 1-second timeout. Once that promise resolves, we will move on to sendMessage’s return statement, which will resolve the promise created by calling sendMessage in the first place.

The Bigger Picture

Finally, let’s return to our original example from above. As a reminder, here it is again without Async/Await:

function taskA() {
  return new Promise(resolve_taskA => setTimeout(resolve_taskA, 750));
}

function taskB() {
  return new Promise(resolve_taskB => setTimeout(resolve_taskB, 250));
}

function work() {
  return new Promise(resolve_work => {
    taskA().then(() => taskB().then(resolve_work));
  });
}

work().then(() => alert("The work is done!"));

Now, instead of manually returning promises from each of the task functions, let’s use the Async and Await to do it for us. Since window.setTimeout takes a callback function rather than returning a promise, we need to “convert” the timeout itself into a promise. We’ll do that in a separate function called sleep. You could imagine that the sleep function would be an in-built feature of JavaScript, an alternative to setTimeout, or maybe it could be a fetch call to a server to retrieve a resource. Either way, it returns a promise that resolves after some amount of time.

function sleep(ms) {
  return new Promise(resolve => setTimeout(resolve, ms));
}

We aren’t using async here because in this instance, we are creating our own promise and returning it, so we don’t need async to do it for us.

Now we’ll convert our tasks to async.

async function taskA() {
  await sleep(750);
}

async function taskB() {
  await sleep(250);
}

We are no longer returning promises from these functions manually, because the async keyword does it for us. We also don’t need to resolve the promise manually because it is automatically resolved when the function returns. However, the await statement prevents the function from returning until the sleep promise inside fulfills itself.

The final task is to give the main work function the Async/Await treatment. We don’t have to return a promise anymore, since async will do that for us. Our goal is simply to fulfill that promise, or return the function, once both tasks have completed in order. Since the tasks themselves are asynchronous and therefore each return promises of their own, we can simply use the await keyword on them!

async function work() {
  await taskA();
  await taskB();
}

Let’s take a look at the completed code:

function sleep(ms) {
  return new Promise(resolve => setTimeout(resolve, ms));
}

async function taskA() {
  await sleep(750);
}

async function taskB() {
  await sleep(250);
}

async function work() {
  await taskA();
  await taskB();
}

Beautiful! We got rid of almost all function nesting (aside from wrapping setTimeout in a promise), and cleaned up our code a lot! Plus, if we ever need to add more tasks, it’s as simple as adding await taskC(); to the work function. Re-ordering the tasks isn’t a chore anymore either!