24. What are the pros and cons of promises over callbacks?
medium
Callbacks and Promises are two popular ways to handle asynchronous operations in JavaScript. Each approach has its own set of benefits and drawbacks, depending on the context in which they are used.
function makeRequest(callback) {
  setTimeout(() => {
    console.log('Request made');
    callback('Data retrieved successfully');
  }, 2000);
}

makeRequest(data => console.log(data)); // 'Data retrieved successfully'
In this example, we define a function called makeRequest that takes a callback function as an argument. The function makes an HTTP request and logs a message when the request is made. It then calls the provided callback function with the retrieved data.
function makeRequest() {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      console.log('Request made');
      resolve('Data retrieved successfully');
    }, 2000);
  });
}

makeRequest().then(data => console.log(data)); // 'Data retrieved successfully'
In this example, we define a function called makeRequest that returns a new Promise. The function makes an HTTP request and logs a message when the request is made. It then resolves the Promise with the retrieved data. We can use the then() method to chain additional asynchronous operations together.

Now let's compare the pros and cons of promises and callbacks:

Pros of Promises:

  • Easier to read and write code
  • More concise syntax
  • Allows for chaining of asynchronous operations
  • Supports error handling using try-catch blocks
  • Can be used with async/await syntax

Cons of Promises:

  • Requires more setup than callbacks
  • May require additional boilerplate code
  • Can be harder to understand for developers who are new to JavaScript

Pros of Callbacks:

  • Simple and easy to understand
  • Widely used in the industry
  • Works well for small-scale applications
  • Allows for passing arguments between functions

Cons of Callbacks:

  • Can lead to nested callbacks, which can be difficult to read and maintain
  • Can make code harder to test and debug
  • May not be suitable for more complex asynchronous operations
In summary, Promises are a powerful tool that can help simplify and streamline asynchronous programming tasks. While they may require more setup than callbacks, their ability to chain operations together and support error handling makes them a better choice for larger-scale applications. However, the simplicity and widespread adoption of callbacks make them a good choice for smaller projects or when working with more experienced developers who are more comfortable with this approach.