Reputation: 79
i have problem with data and socket.io in node.js. It's possible to get data outside socket.on function? Example:
var newdata=new Array();
$(document).ready(function(){
socket.on('Select', function(data){
//console.log(data.products[0][1]);
for(i=0; i<data.products[0].length; i++)
{
newdata.push(data.products[0][i]);
}
console.log(newdata); //array with objects
});
console.log(newdata); //undefined - here i want to get data
Upvotes: 1
Views: 921
Reputation: 1018
You have to use a callback function in this case, because socket.on
is being called asynchronously.
For example, declare a function like this:
function processData(newdata) {
console.log(newdata);
}
Then inside your socket.on('Select', function (data) { ... });
you can call processData(newdata)
, like below:
function processData(newdata) {
console.log(newdata);
}
$(document).ready(function(){
socket.on('Select', function(data){
for(i=0; i<data.products[0].length; i++)
{
newdata.push(data.products[0][i]);
}
processData(newdata);
});
});
Upvotes: 2