Back to Blog Listing

Understanding Async/Await and Promises

JavaScript is a single-threaded runtime environment, which means it executes code sequentially. To perform heavy operations (like network requests, timeouts, or file system access) without blocking the thread, JavaScript uses asynchronous patterns. Let's look at the evolution and best practices of async JavaScript.

The Promise Lifecycle

A Promise is a placeholder for a value that will be resolved or rejected in the future. It exists in one of three states:

  • Pending: Initial state, neither fulfilled nor rejected.
  • Fulfilled: Operation completed successfully.
  • Rejected: Operation failed.
const fetchData = () => {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      const success = true;
      if (success) {
        resolve({ data: "API response" });
      } else {
        reject("Error fetching data");
      }
    }, 1000);
  });
};

fetchData()
  .then(res => console.log(res))
  .catch(err => console.error(err));

Introducing Async/Await

Async/await was introduced in ES2017 to simplify working with promises. By marking a function with the async keyword, you can use the await keyword inside it to pause execution until a promise resolves or rejects, without blocking other threads.

async function displayData() {
  try {
    const result = await fetchData();
    console.log(result.data);
  } catch (error) {
    console.error("Caught error:", error);
  }
}

Parallel vs. Sequential Execution

A common mistake is awaiting multiple unrelated promises sequentially, which leads to slow performance (waterfall effect). Use Promise.all to run them in parallel:

// Sequential (Slow)
const users = await fetchUsers();
const posts = await fetchPosts();

// Parallel (Fast)
const [users, posts] = await Promise.all([fetchUsers(), fetchPosts()]);
💻

Try this code in our online compiler!

Don't just read about it. Write, run, and experiment with these JavaScript concepts instantly on our online workspace with autocomplete suggestions.

Share this tutorial:

CodeCompile