我已经编写了一个Node包,它执行一些密集的数据处理。我可以通过console.log
查看进度,但我希望为最终用户提供一些以事件驱动的方式进行监控的方法。基本上,它类似于返回一个promise,除了每个“步骤”都有一个事件而不是一个then
事件,然后最终使用数据进行解析。
不幸的是,我对Node streams (我猜这是我需要的东西)了解不够,无法做到这一点。我能得到一些建议吗?我如何创建一个流,该流在每次进度增加1%时都会更新,然后最终给出计算数据?
EDIT:作为示例,请考虑以下循环:
for(let i = 0; i < N; i++) {
intensiveFunction();
console.log(`${i} of ${N} completed`);
}
我想要做的是
for(let i = 0; i < N; i++) {
intensiveFunction();
// send user a signal that i/N of the task has been completed
}
发布于 2018-06-04 08:46:58
您不需要使用streams,您可以使用EventEmitter,并发出当前进度或任何您想要的事件。
my-package.js
const EventEmitter = require('events');
// Create a class that extends from EventEmitter
// And now you can emit events when something happens, e.g., progress update
class MyPackage extends EventEmitter {
async intensiveFunction() {
// Something
}
async process() {
for(let i = 0; i < N; i++) {
await this.intensiveFunction();
this.emit('step', i, N); // Or send progress in % or whatever you want
}
}
}
module.exports = MyPackage;
index.js
const MyPackage = require('my-package');
const package = new MyPackage();
package.on('step', (step, total) => console.log(`${step}/${total}`));
package.process();
您可以提供完整的事件API,也可以将其与promises混合使用。这意味着一旦完成,process
就可以解析,或者您可以发出end
事件,或者两者兼而有之。
async process() {
for(let i = 0; i < N; i++) {
await this.intensiveFunction();
this.emit('step', i, N); // Or send progress in % or whatever you want
}
// Emit the end event
this.emit('end', result);
// And resolve the promise
return result; // Whatever result is
}
https://stackoverflow.com/questions/50671959
复制相似问题