Michael Boyd Michael Boyd - 4 months ago 11
Node.js Question

node.js Trying to set multiple variables from multiple requests

So I've been trying to set a global variable from inside a request, but seem to be getting nothing. The code I'm using

A username for testing is test2 after

username=


var forSearching = "test2";
var name = "";

console.log(forSearching);
request("http://mercsystem.esy.es/get.php?username=" + forSearching, function(err, res, body)
{
if (err) return console.error(err);
var main = JSON.parse(body);
if (main.success == "false")
{
message.reply("Sorry, invalid user!")
}
else
{
name = main.Username
}
});

Answer

If you insert a console.log(name) right after you set the value, you will see that the value is set just fine.

The issue is likely one of timing. request() is an asynchronous operation. That means calling request() starts the asynchronous operation, then the rest of your code continues to run to completion and then, some time LATER, the callback gets called with the final asynchronous results.

Though you don't show where you are trying to use the name variable, you are probably checking the value of this global variable before the callback has been called and thus before the value has been set.

In node.js, what you are doing is not how you use asynchronous results. It will never work reliably (or at all). Instead, the only place to use your asynchronous result is in the callback itself or in some function you call from the callback and pass the result to.

var forSearching = "test2";

console.log("begin");
request("http://mercsystem.esy.es/get.php?username=" + forSearching, function (err, res, body) {
    console.log("in request() callback");
    if (err) return console.error(err);
    var main = JSON.parse(body);
    if (main.success == "false") {
        message.reply("Sorry, invalid user!")
    } else {
        var name = main.Username
        console.log(name);          // value shows fine here
        // use the name variable here or call some function and pass
        // the name variable to it
    }
});
console.log("after request() call");

// You cannot use the name value here (even if it was in a global) because
// the async callback has not yet been called

If you ran this code with the console.log() statement I've added, you would see this sequence of events:

 begin
 after request() call
 in request() callback

From this sequence, you can see that code after your request() call runs BEFORE the async callback runs. Thus, you cannot use your name variable there, even if it is in a global.