console.log与return;两个不同的价值观

时间:2014-05-03 13:32:39

标签: node.js http

我在这里有些困惑。我有一个功能,当我使用return我收到undefined时,如果我使用console.log(),我会200 ... < / p>

到目前为止,这是我的代码:

var getStatus = function(subreddit){
    var options = {
        host: "http://www.reddit.com",
        port: 80,
        path: "/r/" + subreddit
    }
    http.get(options, function(res){
        console.log(res.statusCode); // Returns 200
        return res.statusCode; // Returns undefined
    })
}

console.log(getStatus("HIMYM"));

2 个答案:

答案 0 :(得分:1)

您的function(res)会将状态恢复为http.get(),但function(subreddit)不会返回任何内容,因此您会返回undefined

除非http.get()是异步函数,否则以下内容应该有效:

var getStatus = function(subreddit){
    var options = {
        host: "http://www.reddit.com",
        port: 80,
        path: "/r/" + subreddit
    };
    var result;
    http.get(options, function(res){
        console.log(res.statusCode); // Returns 200
        result = res.statusCode; // Returns undefined
    });
    return result;
}

答案 1 :(得分:1)

使用异步调用你需要使用回调来获取值,在http.get()内部返回回调将不会这样做。以下是调用者中使用回调的代码:

var getStatus = function(subreddit, callback){
    var options = {
        host: "http://www.reddit.com",
        port: 80,
        path: "/r/" + subreddit
    }
    http.get(options, function(res){
        console.log(res.statusCode); // Returns 200
        callback( res.statusCode); // Returns to caller's callback
    });
}
getStatus("HIMYM", function(statusCode) {
    console.log(statusCode);
});
相关问题