CodeBlanks Logo Icon CodeBlanks

async function

Learn to define async functions.

What is an async function?

When you put async in front of a function, it becomes an async function. An async function always returns a Promise; the value you return is automatically wrapped in a Promise.

async function greet() {
  return "hi";
}
greet().then(v => console.log(v)); // hi

Here calling greet() gives the same result as Promise.resolve("hi"). Async functions are required to use await inside; they also turn even synchronous errors into Promise rejections.

Async functions and Promise.resolve

The return value of an async function is wrapped in a Promise. If you already return a Promise, no extra wrapping happens; the value is passed through as is.

async function fetchData() {
  return Promise.resolve(42);
}
fetchData().then(v => console.log(v)); // 42

Here fetchData() already returns a Promise, so no extra wrapping happens; then receives 42 directly. This makes async functions interchangeable with ordinary functions that return a Promise.

Practice Your turn: write an async function

Define an async function named greet. Inside it, return the string "hello". Then log the result with greet().then(value => console.log(value)).

Starter code

index.js
// Define async function greet
// Then log the result with .then

Sample solution

index.js
async function greet() {
  return "hello";
}
greet().then(value => console.log(value));

Expected output

hello

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What does an async function return?

  • Always a Promise Correct answer
  • Only numbers
  • Only arrays
  • Undefined

Explanation: An async function's return value is wrapped in a Promise.

2 Fill in the blank: async function

Question
____ function greet() {
  return "hi";
}
greet().then(v => console.log(v));
Answer
async function greet() {
  return "hi";
}
greet().then(v => console.log(v));

Explanation: The async keyword makes the function asynchronous.

3 async function properties

Term Meaning
async prefixes the function
return wraps value in Promise
greet() returns a Promise

All lessons in Beginner