Skip to content

Instantly share code, notes, and snippets.

@harrisonmalone
Last active June 1, 2019 02:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save harrisonmalone/52c78bf1986b82935c75ec2859b0b454 to your computer and use it in GitHub Desktop.
Save harrisonmalone/52c78bf1986b82935c75ec2859b0b454 to your computer and use it in GitHub Desktop.
promise.all demo and small challenge, also showing off promise hell
1) Find a way to push user objects returned from the api into the users array, no loops, only choice was to go into promise hell
2) Using Promise.all get 3 user objects and store them in a users array
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<button>Get data</button>
<script src="./promise-hell.js"></script>
</body>
</html>
// where we store out user objects
const users = []
// event listener on button
const button = document.querySelector("button")
button.addEventListener("click", promiseAll)
// the nicer syntax for handling multiple promises
function promiseAll() {
const userOne = fetch("https://randomuser.me/api/")
const userTwo = fetch("https://randomuser.me/api/")
const userThree = fetch("https://randomuser.me/api/")
Promise.all([userOne, userTwo, userThree])
.then((arrOfRes) => {
arrOfRes.forEach((response) => {
pushUserObjects(response.json())
})
console.log(users)
})
}
// function that pushes object into array
const pushUserObjects = (json) => {
json.then((data) => {
users.push(data.results[0])
})
}
// promise hell
function getUserData() {
fetch("https://randomuser.me/api/")
.then((response) => {
return response.json()
})
.then((data) => {
const user = data.results[0]
users.push(user)
})
fetch("https://randomuser.me/api/")
.then((response) => {
return response.json()
})
.then((data) => {
const user = data.results[0]
users.push(user)
})
fetch("https://randomuser.me/api/")
.then((response) => {
return response.json()
})
.then((data) => {
const user = data.results[0]
users.push(user)
displayResult(users)
})
}
function displayResult(users) {
console.log(users)
}
getUserData()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment