appraisal-rb Logo by Aboling0, CC BY-SA 4.0 kettle-rb Logo by Aboling0, CC BY-SA 4.0 floss-funding Logo by Aboling0, CC BY-SA 4.0 galtzo-floss Logo by Aboling0, CC BY-SA 4.0 omniauth Logo by (presumed) tomeara, (presumed) MIT resque Logo by Resque development team, MIT rubocop-lts Logo by Aboling0, CC BY-SA 4.0 oauth Logo by Chris Messina, CC BY-SA 3.0 ruby-openid Logo by Aboling0, CC BY-SA 4.0

Understanding JavaScript Promises

JavaScript Promises are a powerful feature for handling asynchronous operations. Let’s dive into how they work and when to use them.

What is a Promise?

A Promise is an object representing the eventual completion or failure of an asynchronous operation.

Basic Promise Syntax

const myPromise = new Promise((resolve, reject) => {
  // Asynchronous operation
  if (/* success */) {
    resolve(value);
  } else {
    reject(error);
  }
});

Using Promises

You can use the then() and catch() methods to handle promise results:

myPromise
  .then(result => {
    console.log('Success:', result);
  })
  .catch(error => {
    console.error('Error:', error);
  });

Async/Await

Modern JavaScript provides async/await syntax for working with promises:

async function fetchData() {
  try {
    const response = await fetch('https://api.example.com/data');
    const data = await response.json();
    return data;
  } catch (error) {
    console.error('Error fetching data:', error);
  }
}

Promises make asynchronous code cleaner and easier to reason about!