SmartCodingTips

⏳ Using Async/Await with APIs in JavaScript

Async/Await simplifies working with asynchronous code like API requests. It makes code easier to read and write, especially when dealing with multiple steps in a sequence.

🚀 Basic Example

async function getData() {
  try {
    const response = await fetch("https://jsonplaceholder.typicode.com/posts/1");
    const data = await response.json();
    console.log(data);
  } catch (error) {
    console.error("Error fetching data:", error);
  }
}

getData();

🔍 Breakdown

  • async makes a function return a promise
  • await waits for a promise to resolve
  • try/catch handles errors gracefully

📝 Posting Data Example

async function postData() {
  try {
    const response = await fetch("https://jsonplaceholder.typicode.com/posts", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ title: "Hello", body: "World", userId: 1 })
    });

    const result = await response.json();
    console.log(result);
  } catch (error) {
    console.error("Error posting data:", error);
  }
}

postData();

📌 Why Use Async/Await?

  • Cleaner and more readable than chaining .then()
  • Works just like synchronous code
  • Handles multiple asynchronous steps sequentially
Next Tip: Combine multiple API calls using Promise.all() for parallel execution!