DEV Community

Cover image for Promises vs Callbacks in JavaScript: Understanding Asynchronous Handling
Geampiere Jaramillo
Geampiere Jaramillo

Posted on

1

Promises vs Callbacks in JavaScript: Understanding Asynchronous Handling

When building applications in JavaScript, one of the most important aspects to consider is how to handle asynchronous operations such as API calls, file reading, or database access. To manage these scenarios, two common approaches are widely used: callbacks and promises. I’ll explain their differences, advantages, and when it's best to use each.


What is a Callback?

A callback is a function passed as an argument to another function, which is executed after the main function has completed. It's a common technique for handling tasks that don’t finish immediately.

Basic Example:

function greet(name, callback) {
  console.log("Hello " + name);
  callback();
}

greet("Carlos", function() {
  console.log("Goodbye");
});
Enter fullscreen mode Exit fullscreen mode

Common Issues:

  • Callback Hell: when too many callbacks are nested, making the code hard to read.
  • Complex Error Handling: you have to manually check for errors at every nesting level.

What is a Promise?

A promise is an object that represents the eventual completion (or failure) of an asynchronous operation. It has three states:

  • Pending: the operation is still in progress.
  • Fulfilled: the operation completed successfully.
  • Rejected: the operation failed.

Promise Example:

const promise = new Promise((resolve, reject) => {
  let success = true;

  if (success) {
    resolve("All good");
  } else {
    reject("Something went wrong");
  }
});

promise
  .then(res => console.log(res))
  .catch(err => console.log(err));
Enter fullscreen mode Exit fullscreen mode

Advantages:

  • Better structure than nested callbacks.
  • Centralized error handling using .catch().
  • Ability to chain tasks using .then().

async/await: The Best of Both Worlds

async/await is a modern way to work with promises that allows asynchronous code to be written in a synchronous style.

Example:

async function executeTask() {
  try {
    const result = await promise;
    console.log(result);
  } catch (error) {
    console.log("Error:", error);
  }
}
Enter fullscreen mode Exit fullscreen mode

This makes the code cleaner and more readable, avoiding callback hell and simplifying error handling.


When to Use Each

  • Use callbacks for simple tasks or when working with older libraries.
  • Use promises when you need to manage multiple async tasks or avoid excessive nesting.
  • Use async/await if you want cleaner and more modern code.

Conclusion

Both callbacks and promises are essential for handling asynchrony in JavaScript. Understanding how they work and when to use them will help you write cleaner, more maintainable, and efficient code. As your application grows, promises and async/await become fundamental tools to scale in an organized way.

SurveyJS custom survey software

JavaScript UI Libraries for Surveys and Forms

SurveyJS lets you build a JSON-based form management system that integrates with any backend, giving you full control over your data and no user limits. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more.

Learn more

Top comments (0)

Neon image

Next.js applications: Set up a Neon project in seconds

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Get started →

👋 Kindness is contagious

Explore this insightful post in the vibrant DEV Community. Developers from all walks of life are invited to contribute and elevate our shared know-how.

A simple "thank you" could lift spirits—leave your kudos in the comments!

On DEV, passing on wisdom paves our way and unites us. Enjoyed this piece? A brief note of thanks to the writer goes a long way.

Okay