Promise

A Promise is an object representing the eventual completion or failure of an asynchronous operation. It provides a cleaner way to handle async code compared to callbacks.

States

Pending Initial state, neither fulfilled nor rejected.

Fulfilled Operation completed successfully.

Rejected Operation failed.

Creating Promises

javascript
const promise = new Promise((resolve, reject) => {
  setTimeout(() => {
    const success = true
    if (success) {
      resolve('Success!')
    } else {
      reject('Error!')
    }
  }, 1000)
})

Using Promises

javascript
promise
  .then(result => {
    console.log(result) // 'Success!'
    return processResult(result)
  })
  .then(processed => {
    console.log(processed)
  })
  .catch(error => {
    console.error(error)
  })
  .finally(() => {
    console.log('Done!')
  })

Promise Methods

javascript
// Wait for all promises
Promise.all([promise1, promise2, promise3])
  .then(results => console.log(results))

// Wait for first to resolve
Promise.race([promise1, promise2])
  .then(result => console.log(result))

// Wait for all to settle
Promise.allSettled([promise1, promise2])
  .then(results => console.log(results))

// Return first fulfilled promise
Promise.any([promise1, promise2])
  .then(result => console.log(result))

Async/Await

Modern syntax for working with Promises:

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

Learn More