0

I am having trouble understanding co and how to leverage its functionality inside of another generator. Essentially I have a generator that needs to perform a SQL query, then do something complicated with each row before Yielding them out to the calling function (in the of loop).

The someGen code doesn't look right to me, and it isnt working as expected. So my question is twofold. First how can I leverage co-mysql inside of a generator yielding out objects created out of each row. Second I am struggling where to use co, and more importantly why.

No functioning attempt:

const co = require('co')
    , mysql = require('co-mysql')
    , MYSQL_RECORD_SET = 0

let pool = null
let getConnectionPool = function(){
    if(!pool) pool = mysql.createPool(config.db);
    return pool
}

let someGen = function*() {
    co(function*() {
        let connection = getConnectionPool()
        let recordset = yield connection.query('SELECT ? as jobId', [ 99 ]);

        if (recordset && recordset[MYSQL_RECORD_SET]) {
            var jobs = _.map(recordset[MYSQL_RECORD_SET], function (row) {
                return {id: row.jobId }
            })
            yield jobs
        }
    })()
}

for (let job of someGen()) {
    console.log(job)
}
akaphenom
  • 6,728
  • 10
  • 59
  • 109

1 Answers1

0

This is "working" -- but is not what I was originally shooting for. The someGen now executes the query, but returns an array of objects, rather than yielding them individually...

let someGen = function *() {
    let connection = getConnectionPool()
    let recordset = yield connection.query('SELECT ? as jobId', [ 99 ]);
    if (recordset && recordset[MYSQL_RECORD_SET]) {
        return _.map(recordset[MYSQL_RECORD_SET], function (row) {            
            return { jobId: jobId }
        })
    }
}

let runIt = function() {
    var doSomething = function(job){
    }

    co(function*() {
        let jobBatch = yield someGen()
        _.each(jobBatch, function(job){
            doSomething(job) ;
        })
    })()
}

Still looking for a better answer.

akaphenom
  • 6,728
  • 10
  • 59
  • 109
  • Do you want to be able to yield each item one at a time? Then I don't think you need co, you would just iterate through the result list and yield each element in the someGen function and then use the .next() function all generators have to pull each result out. – Stefano Sep 25 '14 at 10:38
  • That was the goal to yield them out one at a time. What are the CO use cases? – akaphenom Sep 25 '14 at 16:14
  • I'm not 100% sure tbh, I think it lets you run generator functions without having to invoke them as generators using the next() function. This is useful when all you're yielding is just wrapped asynchronous functions. Personally I use the Bluebird Promise library and just yield promisified api calls so I've not had a need to use co. – Stefano Sep 26 '14 at 15:17