DEV Community

Lam
Lam

Posted on

1 1

Promises Cheat Sheet

[Reference] Converting other promises

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

return Promise.reject('reason')

Promise.resolve(result).then(() => {
  /* ... */
})
Enter fullscreen mode Exit fullscreen mode

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

[Reference] Multiple promises

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

[Reference] Consuming promises

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

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

[Reference] Creating promises

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

Use new Promise to create new promises.

[Reference] Introduction

Intro: A quick reference to the JavaScript Promise API.

Speedy emails, satisfied customers

Postmark Image

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay