Skip to content

Instantly share code, notes, and snippets.

@N-Gibson
Last active November 17, 2019 23:36
Show Gist options
  • Save N-Gibson/3015b10e194a7825c484564dc3a8753a to your computer and use it in GitHub Desktop.
Save N-Gibson/3015b10e194a7825c484564dc3a8753a to your computer and use it in GitHub Desktop.

#Promise Practice

  return new Promise((resolve, reject) => {
    if(num > 10) {
      resolve(`${num} is greater than 10`)
    } else {
      reject(Error(`${num} is less than 10`))
    }
  })
}

testNum(90)
  .then(result => console.log(result))
  .catch(err => console.error(err))

const words = ['cheese', 'bread', 'salami', 'apple'];

function makeAllCaps(words) {
  return new Promise((resolve, reject) => {
    if(words.every(val => typeof val === 'string')) {
      resolve(words.map(word => word.toUpperCase()))
    } else {
      reject(Error('Strings only please!'))
    }
  })
}

function sortWords(words) {
  return new Promise((resolve, reject) => {
      resolve(words.sort())
  })
}

makeAllCaps(words)
  .then(words => sortWords(words))
  .then(result => console.log(result))
  .catch(err => console.error(err))
  • .then() is used to perform an action with a resolved promise object whereas .catch() is used to perform an action with a rejected promise.

  • Any kind of async code would be a good case for a promise but using it along side a fetch has been essential.

  • Promises can be used in frameworks like Angular and react as well as other libraries like jQuery.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment