0

I have the following code

index: function (req, res) {

  var Request = unirest.get("https://poker.p.mashape.com/index.php?players=4").headers({ "X-Mashape-Authorization": "xxxxxxxxxxxxxxxxx" }).end(function (response) {
    players = response.body;

    showdown_total = players.showdown.length;
    showdown = Array();


  });
  console.log(players);

  // Send a JSON response
  res.view({
    hello: 'world',
    //players: players
  });

},

It works great if I add the res.view inside unirest get, but I want to send those variables to the view and be able to add another unirest request

Thanks for your help

robzdc
  • 312
  • 2
  • 12

2 Answers2

2

That is how asynchronous code works in Node.js.

Basically, when an operation doesn't evaluate ASAP, node doesn't wait for it. It just says, "fine, no worries, just tell me when you are done".. sort of.

The thing is, in your code, you don't tell node when your get request. is done. You just fire away the view to the client before the request function even starts thinking about fetching the data.

How to make node wait ?

You have some options. Either, give it a callback function (do this when you are done), or you have to nest your functions. Those two are kind of the same thing really.

I'll show you one solution, nested functions:

var urlOne = "https://poker.p.mashape.com/index.php?players=4",
    urlTwo = "http://some.other.url",
    headers = { "X-Mashape-Authorization": "xxxxxxxxxxxxxxxxx" };

// Run first request
unirest.get(urlOne).headers(headers).end(function (response) {
    players = response.body;
    showdown_total = players.showdown.length;
    showdown = Array();

    // Run second request
    unirest.get(urlTwo).headers(headers).end(function (response) {
        someVar = response.body;

        // Show all my data to the client
        res.view({
            players: players,
            someOther: someVar
        });
    });
});

Other solutions:

  • If you don't want to nest the functions, give them a callback to run when they are done.
  • Use a module for handling asynchronous code, for example one of the more popular ones called Async.

I would suggest you to read more about callbacks, asynchronous code and nodejs before jumping directly on the external libraries.

Community
  • 1
  • 1
aludvigsen
  • 5,893
  • 3
  • 26
  • 37
0

There is another way....you could use fibers!

Read some docs here!

var sync = require('synchronize');

index: function (req, res) {
    sync.fiber(function(){

        var response = sync.await(
            unirest.get("https://poker.p.mashape.com/index.php?players=4").headers(
                { "X-Mashape-Authorization": "xxxxxxxxxxxxxxxxx" }
            ).end(sync.defer())
        );

        var players = response.body;
        console.log(players);

        // Send a JSON response
        res.view({
            hello: 'world',
            players: players
        });
    });
}
InternalFX
  • 1,475
  • 12
  • 14