Sobes.tech
Junior — Middle

Can you explain the concept of promises in JavaScript and how they are used for handling asynchronous operations?

sobes.tech AI

Answer from AI

Promises in JavaScript are objects that represent the result of an asynchronous operation and allow you to work with it once the operation completes (successfully or with an error). They help avoid "callback hell" and make code more readable.

A promise can be in three states:

  • pending — the operation is not yet completed;
  • fulfilled — the operation completed successfully;
  • rejected — the operation failed with an error.

To create a promise, the Promise constructor is used, which takes a function with two parameters: resolve and reject. When the asynchronous operation finishes, resolve (success) or reject (error) is called.

Example of using a promise:

function fetchData() {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      const success = true; // simulation of result
      if (success) {
        resolve('Data received');
      } else {
        reject('Error fetching data');
      }
    }, 1000);
  });
}

fetchData()
  .then(result => {
    console.log(result); // 'Data received'
  })
  .catch(error => {
    console.error(error);
  });

Promises can also be chained, which simplifies sequential processing of asynchronous operations.

Can you explain the concept of promises in JavaScript… - sobes.tech