Async / Await
Why async / await?
Section titled “Why async / await?”Before ES2017, we primarily used Promises with .then()
and .catch()
.
But once calls were chained, the code became hard to read.
➡ async
and await
allow you to write asynchronous code like synchronous code, making it clearer and more readable.
Async function
Section titled “Async function”An async
function always returns a Promise.
async function greet() { return "Hello";}
greet().then(msg => console.log(msg)); // Hello
The await
keyword pauses execution of the async function until the Promise resolves.
This avoids chaining multiple .then()
calls.
function wait(ms) { return new Promise(resolve => setTimeout(resolve, ms));}
async function start() { console.log("Waiting..."); await wait(2000); console.log("Finished after 2 seconds");}
start();
Concrete example: before vs after
Section titled “Concrete example: before vs after”With .then()
Section titled “With .then()”fetch("https://jsonplaceholder.typicode.com/posts/1") .then(response => response.json()) .then(data => console.log(data)) .catch(error => console.error("Error:", error));
With async/await
Section titled “With async/await”async function getPost() { try { let response = await fetch("https://jsonplaceholder.typicode.com/posts/1"); let data = await response.json(); console.log(data); } catch (error) { console.error("Error:", error); }}
getPost();
Same result, but much more readable.
Error handling
Section titled “Error handling”async function test() { try { let response = await fetch("https://jsonplaceholder.typicode.com/posts/1"); let data = await response.json(); console.log(data); } catch (e) { console.error("Error:", e); }}
Best practices
Section titled “Best practices”- Use
async/await
to improve code readability. - Always handle errors with
try/catch
. - ⚠️
await
can only be used inside an async function. - To run multiple Promises in parallel, prefer
Promise.all
rather than sequentialawait
calls.
Example: running multiple Promises in parallel
Section titled “Example: running multiple Promises in parallel”async function loadData() { let [posts, users] = await Promise.all([ fetch("/posts").then(r => r.json()), fetch("/users").then(r => r.json()) ]); console.log(posts, users);}