async function
- Node.js course
- Beginner
- Lesson 94/116
- 5 min
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)); // hiHere 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)); // 42Here 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
// Define async function greet
// Then log the result with .thenSample solution
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
____ function greet() {
return "hi";
}
greet().then(v => console.log(v));
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 |