Search code examples
mysqlnode.jsnode-mysqlkoathunk

Getting data from thunk in node, mysql, koa


I want to get some data out of my MySQL database using Koa and the mysql node package. I was looking at co-mysql, but the readme suggests to use thunkify directly. So I did the following:

const query = thunkify(connection.query.bind(connection));

Which seems to work, as I now can do:

app.use(function * main() {
  const races = yield query(
    "SELECT * FROM `races` where '2016-01-19' between start_date and end_date"
  )(function(err, rows) {
    // rows is the data I need
  });
});

However, I cannot find a way to return/yield the row data from the thunk into my races variable. I log it, and it displays the correct data, but when I try to pass it back, it always returns undefined. I've tried a couple of ways from inside the callback, but I can't seem to figure it out:

return rows yield rows (made the callback a generator function) return yield rows ...

I'm often getting: TypeError: You may only yield a function, promise, generator, array, or object, but the following object was passed: "undefined"


Solution

  • races is an array because you are using thunkify for query. co returns an array for any thunks that call their callback with more than one value (ie. callback(null, 1, 2, 3) returns [1, 2, 3].

    If you were to Promisify query instead, races will be assigned to the first returned value only, which appears to be inline with what you're looking for.

    Here's a code example showing it in practice:

    var co = require("co")
    var promisify = require("bluebird").promisify
    var thunkify = require("thunkify")
    
    function async(callback) {
        callback(null, 1, 2, 3)
    }
    
    var p = promisify(async)
    var t = thunkify(async)
    
    co(function*() {
        let x = yield p()
        let y = yield t()
        console.log(x)
        console.log(y)
    }).then(() => {})
    

    When run, the value of x will be 1 and the value of y will be the array [1, 2, 3].

    You can run it with Tonic here: https://tonicdev.com/56ab7cfc879afb0c002c1d49/56ab7cfc879afb0c002c1d4a