Back

The async keyword explained

The async keyword explained

The concept of asynchronous code is not new in the world of development. For other high level programming languages, such as C++, C#, Java and others it's a known and battle tested concept.

However, in the world of Javascript, due to the single-threaded nature of the language and the Node runtime, it's a relatively brand new concept. Promises were introduced back in ES6, but this was later expanded and simplified by the usage of the async keyword, which was introduced in 2017 (ES8 specification).

When a function in JavaScript is marked as async, it means that it will always return a promise. This is one of the key features of async functions.

Here's a breakdown of how async functions work:

Returning a Promise:

  • An async function always returns a promise. If the function returns a value, that value is automatically wrapped in a resolved promise.
  • If the function throws an error, the returned promise is rejected with that error.

Using await:

  • Inside an async function, you can use the await keyword to pause the execution of the function until a promise is resolved or rejected.
  • The await keyword can only be used within async functions.

Here's an example to illustrate these points:

async function exampleFunction() {
  return "Hello, world!";
}

async function exampleWithAwait() {
  const message = await exampleFunction();
  console.log(message);
}

exampleFunction().then((result) => {
  console.log(result); // Outputs: "Hello, world!"
});

exampleWithAwait(); // Outputs: "Hello, world!"

In this example

  • exampleFunction() is marked as async, so it returns a promise. The promise resolves to the value "Hello, world!".
  • exampleWithAwait() is also an async function. It uses await to wait for the promise returned by exampleFunction() to resolve, and then logs the result.

Here's what happens when exampleFunction() is called

  • The function returns a promise that resolves to "Hello, world!".
  • The then method is used to log the resolved value of the promise.

When exampleWithAwait() is called

  • The await keyword pauses the execution of the function until the promise returned by exampleFunction() resolves.
  • Once the promise resolves, the resolved value ("Hello, world!") is assigned to message and logged to the console.