I am trying to build a simple node service that
I'm just getting started with asynchronous programming in node, in general I'm struggling to understand how to preserve scope between asynchronous calls.
Basically - how do I send the JSON service 'result' back to the original GET request via the 'req'?
I'm using Express and Request, the route handler looks like:
exports.list = function(req, res){
var params = req.query;
var queryParam= params.queryParm;
var restURL = "http://some-json-service.com?queryParam=" + queryParam;
var request = require('request');
request(restURL, function (error, response, body) {
if (!error && response.statusCode == 200) {
var result = JSON.parse(body);
// ? How do I send result back to the req?
}
})
You can literally return the response, so where you have your comment you will do:
request(restURL, function (error, response, body) {
if (!error && response.statusCode == 200) {
var result = JSON.parse(body);
res(result)
}
})
the problem with this approach is that your client request will be pending a response from the second service which is fine if it has to be done. Just be aware of the delay that you might be causing.
Also make sure in case of an error you also return a response.
This seems simple enough, so let me know if I didn't fully understand your question.
Cheers.
Vitor.