Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.