Announcements
This site is in read only until July 22 as we migrate to a new platform; refer to this community post for more details.
Get hands-on experience with 20+ free Google Cloud products and $300 in free credit for new customers.

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 729
2 REPLIES 2