Skip to content

Instantly share code, notes, and snippets.

@jbevis
Created June 27, 2017 01:09
Show Gist options
  • Save jbevis/1a1ab8304b70d474f5924fa6cdf41f7a to your computer and use it in GitHub Desktop.
Save jbevis/1a1ab8304b70d474f5924fa6cdf41f7a to your computer and use it in GitHub Desktop.
Turing FEE Mod4 Prework
// Promises Exercise 1

const testNum = (num => {
  return new Promise((resolve, reject) => {
    if (num > 10) {
      resolve(num + ' is greater than 10, good job')
    } else {
      reject(num + ' is less than 10, no bueno')
    }
  })
})

testNum(13)
 .then(result => console.log(result))
 .catch(error => console.log(error))
 
 testNum(8)
 .then(result => console.log(result))
 .catch(error => console.log(error))
 
// Promises Exercise 2 

const arr1 = ['zeppelin', 'aardvark', 'quixotic']
const arr2 = ['react', 8, 'jquery']

const makeAllCaps = (array) => {
  let capsArr = array.map(item => {
    return typeof item === 'string' ? item.toUpperCase() : null
  })
  
  return new Promise((resolve, reject) => {
    if (!capsArr.includes(null)) {
      resolve(capsArr)
    } else {
      reject('No, the array you passed in contained an element that was not a string!')
    }
  })
}

const sortArray = (capsArr) => {
  return new Promise((resolve, reject) => {
    if (capsArr) {
      resolve(capsArr.sort())
    } else {
      reject('error, non-strings present')
    }
  })
}

makeAllCaps(arr1)
  .then(result => sortArray(result))
  .then(result => console.log(result))
  .catch(error => console.log(error))
  
makeAllCaps(arr2)
.then(result => sortArray(result))
.then(result => console.log(result))
.catch(error => console.log(error))

Questions

  • What is .then() used for, and what is .catch() used for?

    • per MDN: ".then() appends fulfillment and rejection handlers to the promise, and returns a new promise resolving to the return value of the called handler, or to its original settled value if the promise was not handled (i.e. if the relevant handler onFulfilled or onRejected is not a function)."

    • per MDN: "Appends a rejection handler callback to the promise, and returns a new promise resolving to the return value of the callback if it is called, or to its original fulfillment value if the promise is instead fulfilled."

  • What are good use cases for Promises?

    • When you have asynchronous js functions and want to continue to fun the rest of the js file while waiting for aysnchronous functions to resolve, e.g. api calls.
  • What other libraries/functions can you find that uses Promises?

    • .fetch, .get (ajax), libraries include React, jquery, node.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment