Zac Anger's Blog

Promises

05 May, 2016

Important things:

Examples:

const promise = new Promise((resolve, reject) => {
  if (something) {
    resolve(value)
  } else {
    reject(reason)
  }
})

const p = Promise.resolve('something')
p.then(res => console.log(res))
const p2 = new Promise((resolve, reject) => {
  setTimeout(() => resolve('asdf'), 2000)
})
p2.then(res => {
  res += 'ghjkl;'
  console.log(res)
})
p2.then(res => console.log(res)) // this is still 'asdf'

somePromise.then(
  val => console.log('fulfilled', val)
, err => console.error('rejected', err))

pr.then(val => console.log('fulfilled', val))
  .then(null, err => console.error('rejected', err))

const throwProm = new Promise((res, rej) => {
  if (something) {
    throw new Error('rejected')
  } else {
  resolve(stuff)
  }
})
throwProm
.then(val => val + 8)
.then(val => console.log('hey', val))
.catch(err => console.error('err', err.message))

const fulProm = new Promise((res, rej) => res(8))
fulProm
.then(val => val + 8)
.then(val => {throw new Error('failure')})
.then(val => console.log('yay', val))
.catch(err => console.error('error', err.message))

one()
.then(res => Promise.all([res, two(res)]))
  .then(results => /* stuff */)
  .catch(err => /* handle err */)

Submit a bug report