sequence http calls in node js

Hi,

I wanted to hit 2 http api using node-js , I want to hit this calls in sequence as second call depends on first call response. I have written code below and working But any other way to write the same. please suggest me -

@Anil Sagar @Dino

var http = require('http');
var request = require('request');

console.log('node.js application starting again ...');


var svr = http.createServer(function(req, resp) {
    
    var call_1= {
        url: "http://mocktarget.apigee.net/json",
        method: 'GET'
    };

 var call_2= {
        url: "http://mocktarget.apigee.net/json",
        method: 'GET'
    };
    
    


     call_one = function() {
            request(call_1, function(error, response, body) {
                if (!error && response.statusCode === 200) {
                 console.log("success1..."+JSON.stringify(body));
                 var jsonResponse = JSON.parse(body);
                 console.log("firstname1 : "+jsonResponse.firstName);
                call_two("1 call response")


                } else {
                    console.log("failure1...");
                    call_two("")
                }


            });


        };


     call_one();
        
    
     call_two = function(callOneRes) {
         console.log("First call response :"+callOneRes);
            request(call_2, function(error, response, body) {
                if (!error && response.statusCode === 200) {
                 console.log("success..."+JSON.stringify(body));
                 var jsonResponse = JSON.parse(body);
                 console.log("firstname : "+jsonResponse.firstName);


                } else {
                    console.log("failure...");
                }
            });


        };
        
    resp.end('Hello, World!');    
        
});


svr.listen(9000, function() {
    console.log('Node HTTP server is listening');
});
1 2 664
2 REPLIES 2

Please look at using a promise chain.As far as i know Apigee Node.JS supports ES5 so you won't be able to use ES6 features.I have used bluebird with apigee and it works out well.

In your specific use case, it may be simpler to use a promisified version of the request library you are using. Take a look @ https://www.npmjs.com/package/request-promise

Look at the library documentation for sample code

Yes!! Promises!