Menu

gitpiper

Promises Cheat Sheet in April 2024

Last Updated: 14 April 2024

README.md

{:.-three-column}

Introduction

{: .-intro}

intro: A quick reference to the JavaScript Promise API.

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

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

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

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

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.


338+ more cheat sheets for you in April 2024

Subscribe to our Newsletter

Subscribe to get resources directly to your inbox. You won't receive any spam! ✌️

© 2024 GitPiper. All rights reserved

Rackpiper Technology Inc

Company

About UsBlogContact

Subscribe to our Newsletter

Subscribe to get resources directly to your inbox. You won't receive any spam! ✌️