我已经下载了以下示例,该示例显示了如何使用工作线程:
https://github.com/heroku-examples/node-workers-example.git
注意:此示例需要安装并运行 Redis
我想弄清楚的是如何访问从工作线程返回的数据?
我添加了一个具有开始和结束日期的“testData”JSON 对象,并将该 JSON 对象传递给 queue.add
// Kick off a new job by adding it to the work queue
app.post('/job', async (req, res) => {
// This would be where you could pass arguments to the job
// Ex: workQueue.add({ url: 'https://www.heroku.com' })
// Docs: https://github.com/OptimalBits/bull/blob/develop/REFERENCE.md#queueadd
var testData = {
"dateStart": new Date(),
"dateCompleted": null
}
console.log('testData start ' + testData.dateStart);
let job = await workQueue.add( testData );
res.json({ id: job.id });
});
以下是上述函数中日志语句的输出:
07:52:47 web.1 | testData start Mon Apr 13 2020 07:52:47 GMT-0700 (Pacific Daylight Time)
我修改了 workQueue.process 函数以添加结束日期并吐出一些日志语句:
workQueue.process(maxJobsPerWorker, async (job) => {
// This is an example job that just slowly reports on progress
// while doing no work. Replace this with your own job logic.
let progress = 0;
console.log('Processing job', job.id, job.data);
// throw an error 5% of the time
if (Math.random() < 0.05) {
throw new Error("This job failed!")
}
while (progress < 100) {
await sleep(50);
progress += 1;
job.progress(progress)
}
job.data.dateCompleted = new Date();
console.log('ending job ' + JSON.stringify(job.data));
// A job can return values that will be stored in Redis as JSON
// This return value is unused in this demo application.
return {r:job.data};
});
}
这是上述函数的日志输出:
07:52:47 worker.1 | Processing job 76 {
07:52:47 worker.1 | dateStart: '2020-04-13T14:52:47.785Z',
07:52:47 worker.1 | dateCompleted: null }
07:52:52 worker.1 | ending job {"dateStart":"2020-04-13T14:52:47.785Z","dateCompleted":"2020-04-13T14:52:52.831Z"}
现在到了有趣的部分,这里是工作线程完成时捕获的代码。我刚刚添加了日志记录语句
workQueue.on('global:completed', (jobId, result) => {
console.log(`Job completed with result ${result}`);
console.log('result ' + result );
console.log('result.r ' + result.r );
console.log('end ' + result.dateCompleted);
console.log('beg ' + result.dateStart);
//var diff = result.dateCompleted - result.dateStart;
//console.log('duration ' + JSON.stringify( diff ));
});
这是输出:
07:52:52 web.1 | Job completed with result {"r":{"cnt":100,"dateStart":"2020-04-13T14:52:47.785Z","dateCompleted":"2020-04-13T14:52:52.831Z"}}
07:52:52 web.1 | result {"r":{"dateStart":"2020-04-13T14:52:47.785Z","dateCompleted":"2020-04-13T14:52:52.831Z"}}
07:52:52 web.1 | result.r undefined
07:52:52 web.1 | end undefined
07:52:52 web.1 | beg undefined
在我看来,数据似乎是在工作线程中设置的,并且控制台日志语句“知道”它......但我不明白为什么result.r未定义以及为什么我无法访问dateStart 和 dateCompleted 值?
更新:
在我的代码中添加了以下内容:
var res = JSON.parse(result);
console.log('res ' + JSON.stringify(res) );
console.log('res.r.dateStart ' + res.r.dateStart );
这是输出:
08:52:34 web.1 | res {"r":{"dateStart":"2020-04-13T15:52:29.272Z","dateCompleted":"2020-04-13T15:52:34.338Z"}}
08:52:34 web.1 | res.r.dateStart 2020-04-13T15:55:11.965Z