DEV Community

loading...

Promises Cheat Sheet

hoanganhlam profile image Lâm ・1 min read

[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.

Discussion (0)

Forem Open with the Forem app