Are you trying to make a function that would do something like str = getStr()?
If so, just wrap the connection in another function and use callback (I call it next) function.
//next is the callback
var getStr = function (next) {
connection.query(query, function(err, rows) {
if (err) {
//you can just throw and error if you want the caller to handle errors.
//you can pass the error to the next function to make the callback handle the errors.
//return is here to stop the rest of the function from executing.
return next(err);
}
var str = "";
for (i = 0; i < rows.length; i++) {
str += rows[i].name + ",";
}
//you can consider next to be the "return" even though it's a callback.
//You do not need the return keyword here.
next(err, str);
});
Call your function with the following:
getStr(function(err, names) {
if (err) {
//handle error
}
console.log(names);
});
One more thing. That for loop will block the nodejs thread while it's building your string. That's not bad, but it's not great. Just be aware of that.