This question already has answers here:
Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference
                                
                                    (6个答案)
                                
                        
                4年前关闭。
            
        

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


为什么结果是5555?不是7777?我认为eval是全局值,并且if语句会将eval值更新为7777,我认为结果将是7777,但我意识到并非如此。谁能告诉我为什么。对不起,类似的问题。

最佳答案

request中的回调是异步的。

因此,当您调用console.log时,它是在执行request回调之前。尝试登录回调本身

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);
    }
})

09-10 11:09