Skip to content

Instantly share code, notes, and snippets.

@harrisonmalone
Created June 4, 2020 00:32
Show Gist options
  • Save harrisonmalone/f46de07408ec662d7ae6698ac82868fb to your computer and use it in GitHub Desktop.
Save harrisonmalone/f46de07408ec662d7ae6698ac82868fb to your computer and use it in GitHub Desktop.
// Promises
// Core:
// 1. What is fetch and how does it relate to AJAX? What does fetch return? Give a very basic example of fetch.
// AJAX is the terminology that encompasses all the different methods for making HTTP requests from our JavaScript. The two things we need for AJAX to work are: the XMLHTTPRequest() object, and JavaScript itself.
// The way in which fetch relates to AJAX is that fetch is a function makes an HTTP request and is therefore one way in which we can make AJAX requests.
// Promise
const handlePokemon = (pokemon) => {
pokemon.forEach((poke) => {
console.log(poke)
})
}
const promise = fetch('https://pokeapi.co/api/v2/pokemon')
promise
.then((response) => {
return response.json()
})
.then((data) => {
const pokemon = data.results
handlePokemon(pokemon)
})
.catch((err) => console.log(err))
// 2. Why do we use promises?
// To handle the eventual completion or failure of an asynchronous operation
// 3. What are the names of the functions that are related to handling promises (that are called when the promise is fulfilled or fails).
// resolve(), reject()
// resolve() === .then
// reject() === .catch
new Promise((resolve, reject) => {})
// 4. https://edstem.org/courses/4230/lessons/2859/slides/21316
const parseRandomUser = (promise) => {
promise.then((user) => console.log(user))
}
const getRandomUser = (callback) => {
fetch('https://randomuser.me/api/')
.then((response) => {
const promise = response.json()
callback(promise)
})
.catch((err) => console.log(err))
}
getRandomUser(parseRandomUser)
// Advanced:
// 5.
// Write a function called evenPromise that returns a promise. evenPromise will take one argument (which will be expected to be a number), and calls resolve if the number is even, and reject if the number is odd. Pass a string as an argument to the resolve and reject functions that reflects these different outcomes. Now call evenPromise and console.log out the data that results from success and error through the appropriate functions.
const evenPromise = (num) => {
return new Promise((resolve, reject) => {
if (num % 2 === 0) {
resolve('the number is even')
} else {
reject('the number is odd')
}
})
}
evenPromise(3)
.then((message) => console.log(message))
.catch((errMessage) => console.log(errMessage))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment