Reputation: 401
I have just started coding Node. I have a function that name is "add" and there is a mysql query inside the function.
I can't return "row" variable which is inside of the query function.
How can i do this?
Broadcast.prototype.add = function (id) {
var broadcast;
mysql.query("SELECT * from Table WHERE Id='" + id + "'", function(err, row) {
if(!err) {
return row; //it didn't work
broadcast = row; //it didn't work
}
});
};
Upvotes: 0
Views: 130
Reputation: 744
The code after the return
statement (broadcast = row;)
is not excecuted.
You should make them switch position if you want to assign the value of row to broadcast. In your comments however you've written that you want the results to be added to the array broadcast. That's why in the provided awnser you'll find it is an array and the row value is added to it.
Also because it runs in async you will need some callback function when the value has been added. Otherwise logging the broadcast
array to fast may results in a 'still' empty array.
Broadcast.prototype.broadcast = [];
Broadcast.prototype.add = function (id,cb) {
// Use self or bind the function(err,row) to Broadcast instead so you can use a normal this inside that function as well
var self = this;
mysql.query("SELECT * FROM Table WHERE Id='" + id + "'", function(err, row){
// Check for errors
if (err) {return console.log(err);}
// Add the value of row to the broadcast array
self.broadcast.push(row);
// Run the callback function
cb();
});
};
var broadcast = new Broadcast();
broadcast.add(id, callbackFunction = function(){
// Here broadcast should have a value
console.log(broadcast.broadcast);
});
// Here broadcast is likely not to have a value yet because mysql.query is probably executed in async.
console.log(broadcast.broadcast);
Upvotes: 1