SmartCodingTips

Async / Await in JavaScript

async and await are modern keywords in JavaScript that simplify working with Promises. They allow you to write asynchronous code in a clean, readable, and synchronous-like manner.

⚙️ Declaring an Async Function

async function greet() {
    return "Hello, Async!";
}

greet().then(msg => console.log(msg));

⏳ Awaiting a Promise

function fetchData() {
    return new Promise(resolve => {
        setTimeout(() => resolve("📦 Data fetched"), 2000);
    });
}

async function displayData() {
    const data = await fetchData();
    console.log(data);
}

displayData();

await pauses the execution of the async function until the promise resolves.

❗ Error Handling with try...catch

async function loadUser() {
    try {
        const user = await fetchUser(); // imaginary function
        console.log(user);
    } catch (error) {
        console.error("❌ Error:", error);
    }
}

🔁 Multiple Awaits in Sequence

async function run() {
    const res1 = await fetchStep1();
    const res2 = await fetchStep2(res1);
    const res3 = await fetchStep3(res2);
    console.log(res3);
}
💡 Tip: Always use try...catch inside async functions to handle potential rejections safely.

✅ Summary

  • async turns a function into a Promise-returning function.
  • await pauses the function until the Promise resolves.
  • Makes code cleaner and avoids chaining .then().