async/await
- React Native course
- Intermediate
- Lesson 38/116
- 5 min
Learn fetch with async/await.
What is async/await?
async/await is a way to write Promises more readably. You mark a function as async; inside it you wait for a Promise with await. await pauses the function until the Promise resolves; then it returns the value.
Example: async function loadUsers() { const response = await fetch(url); const data = await response.json(); }. Here await fetch(url) waits for the request and assigns the response to response. await response.json() waits for the JSON conversion and assigns the data to data. This syntax is more readable than a then chain; the code reads in order. To catch errors you use a try/catch block; this corresponds to .catch() in a then chain.
useEffect with async
To load data in a React component you use useEffect. But useEffect itself cannot be async; because useEffect must return a function, not a Promise. So you define the async function inside useEffect and call it.
Example: useEffect(() => { async function load() { const res = await fetch(url); } load(); }, []). Here load is an async function; it is called inside useEffect. useEffect itself makes the load() call; this returns a Promise but useEffect does not care. This pattern is the standard way to load data in React. The empty dependency array [] makes the function run only once; it runs once when the component mounts.
Practice Write async loadUsers
Write an async function loadUsers. Inside it assign await fetch("https://api.example.com/users") to const response. Then call console.log(response.status). No need to export.
Starter code
// Write async function loadUsers
// put await fetch call inside
// log the response status codeSample solution
async function loadUsers() {
const response = await fetch("https://api.example.com/users");
console.log(response.status);
}Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match the concept to its role
| Term | Meaning |
|---|---|
async |
Marks the function |
await |
Waits for a Promise |
try/catch |
Catches errors |
fetch |
Makes a request |
2 Why can't useEffect itself be async?
useEffect(() => { /* ... */ }, []);- Because it must return a function, not a Promise Correct answer
- Because React doesn't allow it
- Because it needs a dependency array
- Because async functions are slow
Explanation: useEffect must return a cleanup function, not a Promise.
3 Write the await keyword
const url = "api.example.com/users";
const response = ____ fetch(url);
const url = "api.example.com/users";
const response = await fetch(url);
Explanation: await waits for the Promise to resolve.