Skip to content

Instantly share code, notes, and snippets.

@DWS-paris
Created March 27, 2020 10:03
Show Gist options
  • Save DWS-paris/a7a2590d1c7e784689cb2debf77c8a01 to your computer and use it in GitHub Desktop.
Save DWS-paris/a7a2590d1c7e784689cb2debf77c8a01 to your computer and use it in GitHub Desktop.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Promise all</title>
</head>
<body>
<script>
/*
Declarations
*/
const apiUrl = 'https://jsonplaceholder.typicode.com';
//
/*
Functions
*/
const getAllPosts = () => {
return new Promise( (resolve, reject) => {
// Get all posts
fetch( `${apiUrl}/posts` )
.then( fetchResponse => {
if( fetchResponse.ok ){ return fetchResponse.json() }
else{ return reject(fetchResponse) }
})
.then( jsonData => {
// Define selected post (for thee exercice)
const selectedPosts = [ jsonData[1], jsonData[20], jsonData[30] ]
// Set an empty collection array
let dataArray = [];
// Start an async loop
((async function loop() {
for (let i = 0; i < selectedPosts.length; ++i) {
// Get all inforamtion about the post
const item = await promiseAll(selectedPosts[i])
dataArray.push(item)
}
// return all data
return resolve(dataArray);
})());
})
.catch( fetchError => reject(fetchError) );
})
}
const singlePromise = (endpoint) => {
return new Promise( (resolve, reject) => {
fetch( `${apiUrl}/${endpoint}` )
.then( fetchResponse => {
if( fetchResponse.ok ){ return fetchResponse.json() }
else{ return reject(fetchResponse) }
})
.then( jsonData => resolve(jsonData))
.catch( fetchError => reject(fetchError) );
});
};
const promiseAll = post => {
return new Promise( (resolve, reject) => {
return Promise.all([
singlePromise( 'users/' + post.userId ),
singlePromise( 'posts/' + post.id ),
singlePromise( 'comments?postId=' + post.id )
])
.then( promiseCollectionData => {
return resolve({ user: promiseCollectionData[0], post: promiseCollectionData[1], comments: promiseCollectionData[2] })
})
.then( promiseError => {
return reject(promiseError)
})
})
};
//
/*
Start interface
*/
getAllPosts()
.then( posts => console.log(posts) )
.catch( err => console.log(err) )
//
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment