Question

this is my code:

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

I'm new to javascript closure, this is not working for me as RegisterConnection is returning undefined. But in the function itself, the console.log does print true in the console. What am I doing wrong?

Was it helpful?

Solution

Please, check if this approach works for you:

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
                }
            );
        })
    });
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top