First, you'll want to take a look at request , which is the most popular choice for HTTP requests, because of its simplicity,
Secondly, we can combine the simplicity of the request with the concept of Promises to make several requests in a row, while maintaining the code. Using request-promise
var rp = require('request-promise') var url1 = {} var url2 = {} var url3 = {} rp(url1) .then(response => { // add stuff from url1 response to url2 return rp(url2) }) .then(response => { // add stuff from url2 response to url3 return rp(url3) }) .then(response => { // do stuff after all requests // If something went wrong // throw new Error('messed up') }) .catch(err => console.log) // Don't forget to catch errors
As you can see, we can add as many queries as we want, and the code will remain flat and simple. As a bonus, we were also able to add error handling. Using traditional callbacks, you need to add error handling for each callback, whereas here we need to do this only once at the end of the Promise chain.
UPDATE (09/16): While Promises will take us halfway, further experience has convinced me that only Promises becomes messy when there is a lot of mixing between synchronization, asynchronous code, and especially flow control (e.g. if-else). A canonical way to solve this would be with async / await , however this is still under development and will require transpilation. So generators are the next best solution.
Using co
var co = require('co') var rp = require('request-promise') var url1 = {} var url2 = {} var url3 = {} co(function* () { var response response = yield rp(url1)
UPDATE (12/16) . Now that the latest version of node at the time of writing (7.2.1) supports the --harmony flag asynchronous / waiting behind, you can do this:
const rp = require('request-promise') const url1 = {} const url2 = {} const url3 = {} async function doRequests() { let response response = await rp(url1) // add stuff from url1 response to url2 response = await rp(url2) // add stuff from url2 response to url3 response = await rp(url3) // do stuff after all requests // If something went wrong // throw new Error('messed up') } doRequests() .catch(err => console.log) // Don't forget to catch errors
Prashanth chandra
source share