async await notes 2026-09-01
6. Async / Await (Syntactic Sugar over Promises)
async/await makes asynchronous code look synchronous.
async function getUserAndOrders(userId) { try { const user = await fetchUserData(userId); console.log("User:", user.name); const orders = await fetchUserOrders(user.id); console.log("Orders:", orders); return orders; } catch (error) { console.error("Failed:", error.message); throw error; // re-throw if you want the caller to handle it } } // Calling an async function returns a Promise getUserAndOrders(1) .then(orders => console.log("Done")) .catch(err => console.error(err));
Key points about async/await
- An
asyncfunction always returns a Promise. awaitpauses execution of the async function until the Promise settles.- Use
try/catchfor error handling (much cleaner than.catchchains). - You can still use
Promise.allwithawait:
const [user, posts, comments] = await Promise.all([ fetchUser(1), fetchPosts(1), fetchComments(1) ]);
async await
You can also use the modern async/await syntax (recommended for most code):
async function run() { try { const result = await myPromise; console.log("Success:", result); } catch (error) { console.error("Error:", error.message); } finally { console.log("Cleanup"); } } run();
- Throwing inside
.then()orawaitrejects the promise asyncfunctions always return a promise