2

I need to make 2 http request - the response of the first one will be used in the second. The way I do the request is using the http.get(url, callback) method from the http module. But I assume nodejs spawns another thread for the second http request and responses arrive asynchronously. What I did is it to put the second http request in the callback of the first, it works, but looks like unmaintainable code to me.

Any other ways to do it?

chaosmonk
  • 407
  • 6
  • 13
  • Try `async` http://caolan.github.io/async/ – Dhaval Soni Nov 17 '16 at 11:24
  • Possible duplicate of [How to avoid long nesting of asynchronous functions in Node.js](http://stackoverflow.com/questions/4234619/how-to-avoid-long-nesting-of-asynchronous-functions-in-node-js) –  Nov 17 '16 at 11:37

2 Answers2

2

Late to the party but just reiterating what Dhaval Soni said. If you have async / await syntax at your disposal, then the easiest solution is the following:

// inside "async" function

const asyncResult1 = await requestPromise(`${rootUrl}/posts/1`)

const asyncResult2 = await requestPromise(`${rootUrl}/albums/${asyncResult1.id}`)

Notice how the result of the first async request is used to make the second async request.

g.delgado
  • 523
  • 4
  • 19
  • Also, @Niezborala's response doesn't answer OP's question, which is about serial requests, not parallel requests (which is what `Promise.all` is for). – g.delgado Apr 27 '18 at 19:01
1

I made for you quick example in ES6:

const requestPromise = require('request-promise');

const rootUrl = 'https://jsonplaceholder.typicode.com';

const request1 = requestPromise(`${rootUrl}/posts/1`);
const request2 = requestPromise(`${rootUrl}/albums/1`);

Promise.all([request1, request2])
  .then(values => {
    console.log(values);
  });

You need to install two dependencies:

"request": "^2.78.0",
"request-promise": "^4.1.1"
Niezborala
  • 1,857
  • 1
  • 18
  • 27