Created
December 24, 2017 13:57
-
-
Save diogoca/704edda6094041d476172afb63059e4c to your computer and use it in GitHub Desktop.
JavaScript Promise Example with API
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<script> | |
function fetchPhotos() { | |
return fetch('https://jsonplaceholder.typicode.com/photos'); | |
} | |
function fetchPhoto(id) { | |
return fetch('https://jsonplaceholder.typicode.com/photos/' + id); | |
} | |
function getLastPhotos() { | |
fetchPhotos() | |
.then(photos => photos.json()) | |
.then(photosJson => { | |
return photosJson | |
.slice(0, 5) | |
.map((photo) => photo.id); | |
}).then(idArray => { | |
let promises = []; | |
idArray.forEach((id) => { | |
promises.push(fetchPhoto(id)); | |
}); | |
return Promise.all(promises); | |
}).then(photos => { | |
return photos.map(photo => photo.json()); | |
}).then(photosJson => { | |
photosJson.forEach(photoJson => { | |
photoJson.then(p => console.log(p)); | |
}) | |
}); | |
} | |
getLastPhotos(); | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment