Javascript闭包返回undefined

时间:2014-03-17 13:59:20

标签: javascript closures socket.io

这是我的代码:

var timeNow = function () {
    var time = new Date();
    return ((time.getHours() < 10)?"0":"") + time.getHours() +":"+ ((time.getMinutes() < 10)?"0":"") + time.getMinutes() +":"+ ((time.getSeconds() < 10)?"0":"") + time.getSeconds();
};

var RegisterConnection = function (socketid, AuthToken) {
    request.get("api.php", function(err, res, Response){ //Response will return {"result": true}
        Response = JSON.parse(Response);
        if (!err && res.statusCode === 200 && Response.result) {
            console.log(Response.result); // true on console
            return (String(Response.result));
        }
    });
};

io.sockets.on("connection", function (clientSocket) {
    clientSocket.on("connectionDone", function (data) {
        clientSocket.authToken = data.authToken;
        clientSocket.emit(
            "info", {
                Time: timeNow(), // It's printing the time
                information: RegisterConnection(data.socketid, data.authToken) // It's printing undefined
            }
        );
    });
});

我是javascript闭包的新手,这对我来说不起作用,因为RegisterConnection返回undefined。但是在函数本身中,console.log在控制台中打印为true。我做错了什么?

1 个答案:

答案 0 :(得分:2)

请检查此方法是否适合您:

var timeNow = function () {
    var time = new Date();
    return ((time.getHours() < 10)?"0":"") + time.getHours() +":"+ ((time.getMinutes() < 10)?"0":"") + time.getMinutes() +":"+ ((time.getSeconds() < 10)?"0":"") + time.getSeconds();
};

var RegisterConnection = function (socketid, AuthToken, onSuccess) {
    request.get("api.php", function(err, res, Response){ //Response will return {"result": true}
        Response = JSON.parse(Response);
        if (!err && res.statusCode === 200 && Response.result) {
            console.log(Response.result); // true on console
            onSuccess(String(Response.result));
        }
    });
};

io.sockets.on("connection", function (clientSocket) {
    clientSocket.on("connectionDone", function (data) {
        clientSocket.authToken = data.authToken;
        RegisterConnection(data.socketid, data.authToken, function(result) {
            clientSocket.emit(
                "info", {
                    Time: timeNow(), // It's printing the time
                    information: result
                }
            );
        })
    });
});