How can I assign values inside an anonymous function to global variables, or variables outside its scope. For instance, the example below. console.log(rows) returns the right data, while console.log(result) returns undefined
var result;
this.query(sql).execute(function(error, rows) {
console.log( rows )
result = rows;
});
console.log( result );
Node.js is event driven, meaning that most of the functions are asynchronous. The
executefunction does not return any value, because the “returned” value is in the anonymous function declared as your first argument, which function will be called only when the query has been executed and a value has been returned by the database. So yourresultvariable does not contain any value, because there’s nothing to return yet.** EDIT **
Even after your edit, the line where you log the variable
resultis executed before you assignrowsto it, because the anonymous function is only executed later, when the query is completed.