美好的一天。
今天我正在使用这个复杂的脚本工作,该脚本向服务器端渲染的网站发出请求,获取HTML,打破并抓取一些数据。该脚本有4个阶段:phaseOne,phaseTwo,phaseThree和phaseFour。
哪些阶段具有类似的界面:
class PhaseOne {
constructor(MAP) {
this.MAP = MAP || MAP;
}
// All code related with the phase here.
process() {}
}
所以我在所有阶段都在处理这个MAP对象,并且我在堆栈中调用每个阶段,如下所示:
let phases = require('./phases');
[
// 'Initial',
'PhaseOne',
'PhaseTwo',
'PhaseThree',
'PhaseFour',
].reduce((m, fn) => {
return new phases[fn](m).process();
}, MAP);
一切都很好。我的问题是:某些阶段真的很慢..所有程序都需要30分钟才能完成..我希望在我的终端中看到每个阶段的百分比。
像:
PhaseOne: 10%
PhaseOne: 11%
PhaseOne: 12%
但是我没有任何想法,我找不到一个好的教程来做到这一点..
目前在我的流程函数中我有for循环,if语句..一般情况下我使用命令式样式..
PhaseOne的一个例子:
// In this phase we need the property string in MAP.aguia01 to
// assign the first context and extract the data with regex.
if (typeof this.MAP.aguia01.string === 'undefined') {
cli.fatal(
'MAP doesn\'t have the necessary properties to run in Aguia01 phase. Exiting...'
);
}
for (let month of months) {
this.MAP.aguia01.string += requests.aguia01.apply(this, [month]);
}
for (let info of patterns.aguia01.infos) {
this.MAP.aguia01.infos[info.name] = (
this.MAP.aguia01.string.match(info.pattern)
)[1];
}
for (let line of patterns.aguia01.lines) {
this.MAP.aguia01.lines[line.name] = (
this.MAP.aguia01.string.match(line.pattern)
)[1];
}
那么......是否有可能以命令式的方式做我想要的事情?
感谢。
答案 0 :(得分:0)
有progress个套餐,但仅由您决定如何定义"进度"。您可以定义与已完成状态相对应的多个刻度,然后,您只需在进度条上调用一个方法即可进行"进展"。一个例子:
var ProgressBar = require('progress');
// 10 ticks to complete the task
var bar = new ProgressBar(':bar', { total: 10 });
var timer = setInterval(function () {
// make the bar tick(), each call will make a 10% progress
bar.tick();
if (bar.complete) {
console.log('\ncomplete\n');
clearInterval(timer);
}
}, 100);
答案 1 :(得分:0)
如何在reduce调用之外保留上下文对象的进度?您可以将其设为事件发射器,然后将其传递给您的过程函数。在您的流程功能中,您可以发出进度事件,然后可以记录这些事件。也许是这样的:
let phases = require('./phases');
//set up
let progressMonitor = new require('events')
progressMonitor.on('progress', percentDone => {
console.log(percentDone + '% done')
})
// your existing code
[
// 'Initial',
'PhaseOne',
'PhaseTwo',
'PhaseThree',
'PhaseFour',
].reduce((m, fn) => {
return new phases[fn](m).process(progressMonitor);
}, MAP);
然后在你的流程函数中:
class PhaseOne {
constructor(MAP) {
this.MAP = MAP || MAP;
}
// All code related with the phase here.
process(progressMonitor) {
//do work
progressMonitor.emit('progress', 10)
//more work
progressMonitor.emit('progress', 15)
//much work
progressMonitor.emit('progress', 75)
}
}