🎓 A1Learner
🔍
0 of 50 lessons completed

JavaScript async Functions

An async function always returns a promise. Its return value becomes the fulfilled value of that promise.

An async function returns a promise

The function returns the number 42. The caller gets a promise, and then logs the number once the promise fulfills.

async function getScore() {
  return 42;
}
getScore().then((value) => console.log(value));

Check the return type

The async function returns a value, but the call itself gives back a promise. The instanceof check proves the return type.

async function getName() {
  return "Ada";
}
const result = getName();
console.log(result instanceof Promise);
result.then((value) => console.log(value));

An async function that runs at once

The async IIFE runs its body right away. The body logs first, and the plain line logs after it.

(async () => {
  console.log("Inside async");
})();
console.log("Outside");

Compute a value in an async function

The function doubles its input and returns the result. The caller reads the doubled value with then.

async function double(n) {
  return n * 2;
}
double(21).then((value) => console.log(value));

Example

async function greet(name) {
  return "Hello, " + name + "!";
}
greet("Ada").then((message) => console.log(message));
console.log("Greeting requested");

Key points

  • async function: a function marked with async, which always returns a promise
  • The return value of an async function becomes the fulfilled value.
  • An async function with no return fulfills with undefined.
  • An async function runs its body at once, until it pauses or returns.
  • Callers use then on the returned promise to read the result.
  • Async IIFE: an async arrow function that runs at once, written (async () => { ... })();

In this example, the greet function is async, so its return value becomes a fulfilled promise. The then method logs the greeting after the plain line, because the promise callback runs after the current lines finish.

Try it Yourself

Edit the code, then press Run.

Runs in your browser — the preview under the editor is the real result. Nothing is sent to a server. The code runner panel (right) does the same with more room.

Exercise

What does an async function always return?