Created
October 4, 2017 17:20
-
-
Save jaredatron/8fd20aeb276a83cf42e54eddce7c6acc to your computer and use it in GitHub Desktop.
parallel HTTP requests with Promises
This file contains 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
const request = require('request-promise') | |
const getURL = (url) => { | |
console.log(`GET: ${url}`) | |
// request the URL as a GET requests | |
// parse the resonse using JSON.parse | |
} | |
const getPosts = () => { | |
return getURL('https://jsonplaceholder.typicode.com/posts') | |
} | |
const getPost = (postId) => { | |
return getURL(`https://jsonplaceholder.typicode.com/posts/${postId}`) | |
} | |
const getAllPostsWithDetails = () => { | |
return getPosts().then(posts => { | |
// use Promise.all here | |
// for each post | |
// call getPost(post.id) | |
// then add the results to the post as post.details | |
}) | |
} | |
getAllPostsWithDetails().then(posts => { | |
console.log(JSON.stringify(posts, null, 2)) | |
}) |
This file contains 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
const request = require('request-promise') | |
const getURL = (url) => { | |
console.log(`GET: ${url}`) | |
return request({method: 'GET', url}) | |
.then(json => JSON.parse(json)) | |
} | |
const getURLS = (urls) => { | |
return Promise.all(urls.map(getURL)) | |
} | |
const getPosts = () => { | |
return getURL('https://jsonplaceholder.typicode.com/posts') | |
} | |
const getPost = (postId) => { | |
return getURL(`https://jsonplaceholder.typicode.com/posts/${postId}`) | |
} | |
const getAllPostsWithDetails = () => { | |
return getPosts().then(posts => { | |
return Promise.all( | |
posts.map(post => getPost(post.id)) | |
).then(postDetails => { | |
posts.forEach((post, index) => { | |
post.details = postDetails[index] | |
}) | |
return posts | |
}) | |
}) | |
} | |
getAllPostsWithDetails().then(posts => { | |
console.log(JSON.stringify(posts, null, 2)) | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment