-2

var data is return undefined

Here is the code

var data;
    function my_function(newData) {
        console.log(newData)//Everything is okay here, {name: 'Arnel Cariaga', email: 'sadas@sdfs.sad'}
        data = newData;
    }

    socket.on('hello', function(data) {
        var newData = JSON.stringify(data);
        my_function(newData)
    });
    console.log(data) //I get UNDEFINED HERE

1 Answers1

0

The thing is that you can't really do that. A work around is to wrap the code that will use the data under the .on block.

socket.on('hello', function(data)
 { var newData = JSON.stringify(data);
 my_function(newData) }

//All the code that needs access to the data

);
Algo7
  • 2,122
  • 1
  • 8
  • 19