[英]wrapping co and co-mysql from within a generator function, and yielding out of the wrapping function
I am having trouble understanding co and how to leverage its functionality inside of another generator. 我在了解co以及如何在另一个生成器内部利用其功能方面遇到困难。 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).
本质上,我有一个生成器,需要执行SQL查询,然后在将它们交出给调用函数之前(在of循环中),对每行进行一些复杂的处理。
The someGen code doesn't look right to me, and it isnt working as expected. someGen代码对我而言并不正确,并且无法按预期工作。 So my question is twofold.
所以我的问题是双重的。 First how can I leverage co-mysql inside of a generator yielding out objects created out of each row.
首先 ,我如何在生成器内部利用Co-mysql产生从每一行创建的对象。 Second I am struggling where to use co, and more importantly why.
其次,我正在努力在哪里使用co,更重要的是为什么。
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)
}
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...
someGen现在执行查询,但是返回一个对象数组,而不是单独产生它们……
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. 仍在寻找更好的答案。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.