Search code examples
javascriptfor-loopcallbacksocket.ioreturn

returning data from for loop


i am using socket.io to fetch data about a user using his uid when you run this function

function getUserData(uid){
    "use strict"
    socket.emit('getUserData',uid, function(callback){
        console.log('callback' + callback)
        for (var i = 0; i < callback.length; i++) {
            var row = callback[i];
            var username = row.username;
            var about = row.about;
            var uid = row.uid;
        }
    })        
    return {
                username:  username,
                uid: uid,
             //   about: about
            };
}

and it does this on the server side

socket.on('getUserData',function(uid, callback){
    connection.query('SELECT * FROM users WHERE uid = ?', [uid], function(err, rows) {
        callback(rows)
    })
})

but when i do console.log(getUserData(uid)) i get undefined but i do get the object from the first callback what am i doing wrong here?


Solution

  • The callback from .emit() is asynchronous. That means it happens sometime LATER, long after your getUserData() function has already returned. That means you have to communicate back the result using either a callback or a promise. In addition, it makes no sense that you're trying to iterate an array and return one result. You should either return all the results or pick one particular item from the array as your final value. This resolves with the whole array of data, letting the caller decide which one they want to pick from the array.

    Here's how you could do so with a promise:

    function getUserData(uid){
        "use strict"
        return new Promise(resolve => {
            socket.emit('getUserData',uid, function(returnData){
                console.log('returnData', returnData)
                resolve(returnData);
            });
        });
    }
    
    // usage
    getUserData(someUID).then(results => {
        // use results in here
    });