JavaScript
async functions
Learn how the async keyword makes a function return a promise.
The async keyword
When you put async before a function, that function automatically returns a promise. This makes asynchronous code easier to write.
async function fetchGreeting() {
return "Hello";
}
Here return "Hello" does not give a plain string; JavaScript wraps it with Promise.resolve("Hello"). So the function returns a fulfilled promise. The async keyword alone does not slow the code down; it only guarantees that the return value is a promise.
Non-promise return values
If you already return a promise inside an async function, JavaScript gives it back as is; it does not wrap it again. But if you return a string, number, or object, the value is automatically wrapped with Promise.resolve.
async function one() { return Promise.resolve(10); }
async function two() { return 10; }
Both functions return a fulfilled promise carrying the same value. This consistency lets async functions work smoothly with code that always expects a promise.
Exercise Write an async function
Write an async function called fetchGreeting that returns the string 'Hello'.
Show example solution
async function fetchGreeting() {
return "Hello";
}
Test yourself
-
What does async function f() { return 5; } return?
async function f() { return 5; }
const result = f();
- The number 5
- A promise resolving to 5
- undefined
- It throws an error
Show answer
A promise resolving to 5 — Correct! An async function always returns a promise; the 5 is wrapped inside it.
-
Declare an async function
function fetchUser() {
return { name: "Alex" };
}
// Make the above async:
____ function fetchUser() {
return { name: "Alex" };
}
Show answer
function fetchUser() {
return { name: "Alex" };
}
// Make the above async:
async function fetchUser() {
return { name: "Alex" };
}
-
Match async function behaviors
- async function f() { return 5; }
- returns Promise.resolve(5)
- async function f() { return p; }
- returns p unchanged if p is a promise
- async function f() { }
- returns Promise.resolve(undefined)
- async function f() { throw x; }
- returns a rejected promise
Next lesson: The await operator