li *_*i x 5 javascript progress promise bluebird
对于如何使用时,错误处理大量的信息promise.all()
使用catch
,但我想要做到的,是来处理每一个时间,在这里面一个承诺promise.all()
解决.我试图这样做的原因是因为我试图在控制台中设置自定义进度条,我需要在每次解析一个promise时调用tick方法.
this.getNewSources = function () {
var bar = new ProgressBar(':bar', {total: this.getSourceMap().size});
var timer = setInterval(function () {
bar.tick();
if (bar.complete) {
console.log('\ncomplete\n');
clearInterval(timer);
}
}, 100);
let promiseArr = [];
for (let x of this.getSourceMap().values()) {
promiseArr.push(this.requestArticles(x.getName(), x.getCat(), x.getKey()));
}
return Promise.all(promiseArr).then(() => {
console.log("Articles loaded this round: " + this.articles.size);
console.log('all sources updated');
this.loadedArticles = true;
console.log(this.articleCount);
console.log(this.articles.size);
}).catch(e => {
console.log(e);
});
};
Run Code Online (Sandbox Code Playgroud)
我正在试图找出一种能够bar.tick()
在每个单独的承诺解决时调用该方法的方法.
(回答我自己的问题。)
我通过添加一个处理程序来处理它then
,我从中获得承诺requestArticles
(我将它们推入promiseArr
数组)。我必须确保传递处理程序从处理程序接收到的值,以便它传播到Promise.all
,请参阅***
以下行:
this.getNewSources = function () {
var bar = new ProgressBar(':bar', {total: this.getSourceMap().size});
var timer = setInterval(function () {
if (bar.complete) {
console.log('\ncomplete\n');
clearInterval(timer);
}
}, 100);
function updateProgressBar() {
bar.tick()
}
let promiseArr = [];
for (let x of this.getSourceMap().values()) {
promiseArr.push(this.requestArticles(x.getName(), x.getCat(), x.getKey())
.then(value => { // ***
updateProgressBar(); // ***
return value; // ***
}) // ***
);
}
return Promise.all(promiseArr).then(() => {
console.log("Articles loaded this round: " + this.articles.size);
console.log('all sources updated');
this.loadedArticles = true;
console.log(this.articleCount);
console.log(this.articles.size);
}).catch(e => {
console.log(e);
});
};
Run Code Online (Sandbox Code Playgroud)
这样,当承诺单独完成时,我的处理程序就会被调用,并且由于我正在返回收到的值,因此我的调用创建的承诺将then
使用该值进行解析,这Promise.all
将看到。拒绝将跳过该处理程序并直接转到 所连接的处理程序Promise.all
。
控制台输出结果:
(感谢TJ Crowder最初的解释,这让我意识到我可以在推入数组时执行此操作。他说他更喜欢删除该答案并让我发布此答案。)