Using Async and Await
async and await are keywords that let you write promise-based code, such as HTTP requests with fetch, in a style that reads from top to bottom like ordinary synchronous code. Instead of chaining .then() calls, you pause inside a function until a promise settles and get its value directly. They are now the most common way to make HTTP requests in React apps and in Node.
The two keywords and what they do
Putting async before a function does two things: it allows await inside that function, and it makes the function always return a promise. If you return a value, the promise fulfils with it; if you throw, the promise rejects.
await placed before a promise pauses the async function until that promise settles. If it fulfils, await gives you the value. If it rejects, await throws the error at that line, so you can catch it with an ordinary try/catch. Only the async function pauses; the rest of the page or server keeps running.
Rewriting a GET request
Here is the GET request from the previous lesson written both ways.
// With .then()
function loadPosts() {
return fetch('https://jsonplaceholder.typicode.com/posts')
.then((response) => response.json())
.then((posts) => posts.slice(0, 5));
}
// With async/await
async function loadPosts() {
const response = await fetch('https://jsonplaceholder.typicode.com/posts');
const posts = await response.json();
return posts.slice(0, 5);
}
Notice the two awaits. The first waits for the response headers to arrive. The second waits for the body to download and be parsed as JSON, because response.json() also returns a promise.
Using it inside a React component
The callback passed to useEffect must not be an async function, because React expects it to return either nothing or a cleanup function, not a promise. Define an async function inside the effect and call it.
function PostList() {
const [posts, setPosts] = useState([]);
const [isLoading, setIsLoading] = useState(true);
useEffect(() => {
async function fetchPosts() {
try {
const response = await fetch('/api/posts');
const data = await response.json();
setPosts(data);
} catch (err) {
console.error('Request failed:', err);
} finally {
setIsLoading(false);
}
}
fetchPosts();
}, []);
if (isLoading) return <p>Loading...</p>;
return (
<ul>
{posts.map((post) => <li key={post.id}>{post.title}</li>)}
</ul>
);
}
The finally block runs whether the request succeeded or failed, which makes it the right place to switch off a loading spinner.
Watch out for accidental waiting in a row
Each await pauses until its promise settles. If you write const users = await getUsers(); followed by const posts = await getPosts();, the second request does not even start until the first finishes, even though they do not depend on each other. That can double the loading time. Start both requests first and wait for them together:
const [users, posts] = await Promise.all([getUsers(), getPosts()]);
Another trap is forgetting await. Without it, you get a pending promise object instead of the data, and code like data.map fails with "map is not a function". If something shows up as Promise {<pending>} in the console, a missing await is the likely cause.
Also note that fetch only rejects on network failures. A 404 or 500 response still fulfils, so the catch above will not see it. Checking response.ok is covered in the next lesson on handling HTTP errors.
Points to keep
asyncfunctions always return a promise.awaitunwraps a promise's value or throws its error.- Use
try/catch/finallyfor errors and loading state. - Run independent requests in parallel with
Promise.all.
Ready to master real-world web development?
Learn HTML, CSS3, Bootstrap and JavaScript hands-on with mentor-led sessions.