Sobes.tech
Junior — Middle

Can you explain what a Promise is and how it is used in asynchronous programming?

sobes.tech AI

Answer from AI

Promise is an object in JavaScript that represents the result of an asynchronous operation, which may succeed or fail in the future. Promise allows writing asynchronous code more readably, avoiding "callback hell."

A Promise has three states:

  • pending — initial state,
  • fulfilled — the operation completed successfully,
  • rejected — the operation failed.

Using Promise, you can chain methods .then() to handle successful results and .catch() to handle errors.

Example:

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

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

Thus, Promise helps manage asynchronous operations and their results more conveniently and clearly.