How do I return results from callback?

245 views
Skip to first unread message

Ben Strawn

unread,
Nov 22, 2012, 10:17:22 PM11/22/12
to node-...@googlegroups.com
My goal is to return data from the callback of a query. In the example code, the results in the callback are just printed out to the system, so it doesn't show how to get that data back to your program. I've looked through the node-mysql code a bit, but couldn't figure out everything in the returned Sequences.Query object. As an example, here's some of my code:

connection.query(query, function(err, rows) {
    if (err) throw err;
    var str = "";

    for (i = 0; i < rows.length; i++) {
        str += rows[i].name + ",";
    }
});

So how do I send str back to my program?

Christian Tellnes

unread,
Nov 23, 2012, 5:06:18 AM11/23/12
to node-...@googlegroups.com
You dont.
You continue your program inside the callback. The callback is called sometime later when the data arrives.
--
You received this message because you are subscribed to the Google Groups "node-mysql" group.
To view this discussion on the web visit https://groups.google.com/d/msg/node-mysql/-/ldG3miNNXkIJ.
To post to this group, send email to node-...@googlegroups.com.
To unsubscribe from this group, send email to node-mysql+...@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/node-mysql?hl=en.


--
Mvh. Christian Vaagland Tellnes
http://christian.tellnes.com/

Ryan Lee

unread,
Nov 30, 2012, 1:43:14 PM11/30/12
to node-...@googlegroups.com
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.
Reply all
Reply to author
Forward
0 new messages