Promises
A cheatsheet by @rstacruz|Refreshed 7 months ago.Refresh|View source on Github

Introduction

Introduction

intro: A quick reference to the JavaScript Promise API.

Creating promises

Creating promises

new Promise((resolve, reject) => {
  doStuff(() => {
    if (success) {
      resolve('good')
    } else {
      reject(new Error('oops'))
    }
  })
})

Use new Promise to create new promises.

Consuming promises

Consuming promises

promise
  .then((result) => {
    /* success */
  })
  .catch((error) => {
    /* failure */
  })

then() runs a function when a promise resolves. catch() runs when a promise fails.

Multiple promises

Multiple promises

const promises = [promise1(), promise2() /* ... */]
// Succeeds when all succeed
Promise.all(promises).then((results) => {
  /* ... */
})
// Succeeds when one finishes first
Promise.race(promises).then((result) => {
  /* ... */
})

Converting other promises

Converting other promises

return Promise.resolve('result')
return Promise.resolve(promise)
return Promise.resolve(thenable)

return Promise.reject('reason')

Promise.resolve(result).then(() => {
  /* ... */
})

Promise.resolve(val) will return a promise that resolves to the value given to it.