【发布时间】:2016-04-13 09:29:13
【问题描述】:
目前我有以下代码:
var detailPromises = links.map(function (link) { return requestP(link) });
var oldPollNames = [];
// add a database call to the promises as it also can resolved during detail fetching
detailPromises.push(db.polls.findAsync({}, {title: 1}));
return Promise.all(detailPromises)
.then(function (data) {
oldPollNames = data.pop().map(function (item) { return item.title; });
return data;
})
.then(function (htmls) {
var newPolls = [];
htmls.forEach(function (i, html) {
// some processing of html using oldPollNames (newPools.push...)
});
return newPolls;
})
.then(/* insert into db */);
我在做的是:等待db+等待html请求,然后处理booth。
我想知道执行以下操作是否更有意义/更高效:
var detailPromises = links.map(function (link) { return requestP(link) });
return db.polls.findAsync({}, {title: 1}).then(function(polls) {
var oldPollNames = polls.map(function (item) { return item.title; });
var newPolls = [];
detailPromises = detailPromises.map(function (p) {
return p.then(function (html) {
// some processing of html using oldPollNames (newPools.push...)
})
});
return Promise.all(detailPromises)
.done(function () {
// insert newPolls into db
});
});
imo 的第二种方法的优点是每个请求在完成时都(已经)得到处理,并且可以在所有/其他承诺都实现之前进行处理。
【问题讨论】:
-
你使用的是什么承诺库?
.done是什么? -
你真的应该使用
map而不是forEach和newPolls数组。 -
@Bergi 你是对的,否则 Promise.all 不会等待所有处理(newPools.push ...)完成。谢谢
-
@Bergi done 用于promisejs.org 但我实际上不知道他们为什么使用它lol
-
啊,我明白了。 They say:“请注意,promise.done(在本节示例中用作教具)尚未标准化。”。你不应该使用它,总是去
then。
标签: javascript promise