0
var request = require('request');
var cheerio = require('request');
var eval = "5555";

request('http://google.com', function (error, response, body) {
    if (!error && response.statusCode == 200) {
        var keys = body.split(",");
        eval = keys[0]; // Think keys[0] is 7777
// and no problem in if statement, it must be excuted.
    }
})

console.log("evalue :"+eval);
// result ---> 5555  

Why the result is 5555? not 7777? I think eval is global value, and if statement will update eval value to 7777, and I think the result will be 7777 but I realize it doesn't. Can anyone tell me why. Sorry to similar question.

ton1
  • 7,238
  • 18
  • 71
  • 126

3 Answers3

2

The callback in request is asynchronous.

Therefore, when you call console.log, it is before the request callback is executed. Try logging in the callback itself

request('http://google.com', function (error, response, body) {
    if (!error && response.statusCode == 200) {
        var keys = body.split(",");
        eval = keys[0]; // Think keys[0] is 7777
        console.log("evalue :"+eval);
    }
})
AmmarCSE
  • 30,079
  • 5
  • 45
  • 53
1

You are doing an asynchronous task. The callback function does not necessarily runs before the console.log.

This is the nature of javascript non-blocking IO. When you need to do an IO operation, you can pass a callback, when the IO finishes, it will invoke your callback, meanwhile CPU is free to do other procedures in your JS file.

Aᴍɪʀ
  • 7,623
  • 3
  • 38
  • 52
0

Because console.log is executed before above request's response has arrived since this is an asynchronous execution. Try putting the console.log inside that anonymous function to get the value you want.

request('http://google.com', function (error, response, body) {
    if (!error && response.statusCode == 200) {
        var keys = body.split(",");
        eval = keys[0]; // Think keys[0] is 7777
        console.log(eval);
    }
})
gurvinder372
  • 66,980
  • 10
  • 72
  • 94