This question already has answers here:
How do I return the response from an asynchronous call?
                                
                                    (36个答案)
                                
                        
                                5年前关闭。
            
                    
这是我的代码:

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返回未定义。但是在函数本身中,console.log在控制台中确实显示为true。我究竟做错了什么?

最佳答案

请检查这种方法是否适合您:

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

09-25 15:07