Hans
Hans

Reputation: 2910

node.js multiple http requests

I am a newbie to node and js and try to create a website in express that makes three Rest API calls before rendering the page. At the moment I have the below, which returns some json which I convert into a list of objects.

Some of these properties only return id values and I would like to run three more API requests that return lookups on these Id's so that I can present this data to the user as meaningful values.

I could do this synchronously by running the next API call where I am currently rendering the index page, but that looks really messy. All the async tutorials I have seen confuse the hell out of my newbie way of thinking though. Can someone post an easy to follow example for async that somewhat reflects the below structure?

var issues_json = "";
var request = http.request(options, function(response) {
    console.log("statusCode: ", res.statusCode);
    console.log("headers: ", res.headers);

    response.on("data", function(data) {
        issues_json += data;
    });

    response.on("end", function() {
        console.log(issues_json);
        var column_obj = JSON.parse(issues_json);
        res.render('index', {
            title: 'List of Issues',
            response: issues_json,
            objects: column_obj
        });
    });

    response.on("error", function(e) {
        console.log(e.Message);
        res.render('index', {
            title: 'error',
            e: e.Message
        });
    });
});
request.end();

Upvotes: 6

Views: 13990

Answers (2)

user1893436
user1893436

Reputation: 1

check this out: https://github.com/JacksonTian/eventproxy. It's a js lib which makes async calls into events. The only difference from the ticked answer is its way of writing code.

Upvotes: 0

3on
3on

Reputation: 6339

You should use Request

You would have something like

app.get("/route", function(req, res) {

  var callbackThree = function(error, resp, body) {
    var data = JSON.parse(body);
    res.send({title; "My Title", data: data});
  }

  var callbackTwo = function(error, resp, body) {
    request("api.com/42", callBackThree);
  }

  var callbackOne = function(error, resp, body) {
    request("api.com/things", callBackTwo);
  }

  request("api.com/users", callBackOne);
}

Upvotes: 4

Related Questions