DEV Community

rashidpbi
rashidpbi

Posted on

๐Ÿงต Understanding JavaScript Promises, Callbacks & Handling Multiple Async Tasks

JavaScript is single-threaded, yet it handles tasks like API calls, timers, and user interactions efficiently โ€” thanks to callbacks and promises. Let's explore how these tools work together and how to manage multiple async operations.

๐Ÿง  Callback & Asynchronicity

A callback is a function passed into another function to run later โ€” perfect for async tasks like fetching data or waiting for a timeout.

setTimeout(() => {
  console.log("This runs later");
}, 1000);
Enter fullscreen mode Exit fullscreen mode

But callbacks can lead to callback hell, making code hard to read and maintain.

๐Ÿš€ Enter Promises

A Promise represents a value that may be available now, later, or never.

const fetchData = new Promise((resolve, reject) => {
  setTimeout(() => resolve("Done!"), 2000);
});

fetchData.then(console.log).catch(console.error);
Enter fullscreen mode Exit fullscreen mode

Using async/await improves readability even more:

async function getData() {
  try {
    const result = await fetchData;
    console.log(result);
  } catch (err) {
    console.error(err);
  }
}
Enter fullscreen mode Exit fullscreen mode

๐Ÿ”„ Handling Multiple Promises

JavaScript provides powerful utilities for handling multiple promises at once:

โœ… Promise.all([...])

Waits for all promises to resolve. Fails fast if any reject.

Promise.all([p1, p2, p3])
  .then(console.log)
  .catch(console.error);
Enter fullscreen mode Exit fullscreen mode

๐Ÿง˜ Promise.allSettled([...])

Waits for all to settle (resolve or reject) and returns results for each.

Promise.allSettled([p1, p2, p3]).then(console.log);
Enter fullscreen mode Exit fullscreen mode

๐Ÿ Promise.race([...])

Returns the first settled (resolve or reject) promise.

Promise.race([p1, p2]).then(console.log).catch(console.error);
Enter fullscreen mode Exit fullscreen mode

๐Ÿฅ‡ Promise.any([...])

Returns the first fulfilled promise. Ignores rejections unless all fail.

Promise.any([p1, p2]).then(console.log).catch(console.error);
Enter fullscreen mode Exit fullscreen mode

๐Ÿงฉ Final Thoughts

  • Callbacks introduced async flow.
  • Promises simplified it.
  • Promise combinators (all, allSettled, race, any) give us flexible control over multiple tasks.
  • Use async/await for cleaner, more readable code.

Top comments (0)