Skip to content

Instantly share code, notes, and snippets.

@jaredatron
Created October 4, 2017 17:20
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 jaredatron/8fd20aeb276a83cf42e54eddce7c6acc to your computer and use it in GitHub Desktop.
Save jaredatron/8fd20aeb276a83cf42e54eddce7c6acc to your computer and use it in GitHub Desktop.
parallel HTTP requests with Promises
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))
})
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