[英]Waiting on multiple map methods to return using promises and then get all maps return values
在一個快速項目中,我有2個映射,它們都通過一個puppeteer實例運行,並且都返回數組。 當前,我正在使用Promise.all在兩個映射上等待完成,但是它只返回第一個數組的值,而不是第二個數組的值。 我該如何做才能得到兩個映射變量的結果?
const games = JSON.parse(JSON.stringify(req.body.games));
const queue = new PQueue({
concurrency: 2
});
const f = games.map((g) => queue.add(async () => firstSearch(g.game, g.categories)));
const s = games.map((g) => queue.add(async () => secondSearch(g.game, g.categories)));
return Promise.all(f, s)
.then(function(g) {
console.log(g); //only returns `f` result, not the `s`
});
Promise.all接受Promises數組作為參數。 您需要將兩個數組作為單個數組參數傳遞
return Promise.all(f.concat(s))
.then(function(g) {
console.log(g); //only returns `f` result, not the `s`
});
不需要使用PQueue,bluebird已經開箱即用地支持:
(async () => {
const games = JSON.parse(JSON.stringify(req.body.games));
let params = { concurrency: 2};
let r1 = await Promise.map(games, g => firstSearch(g.game, g.categories), params);
let r2 = await Promise.map(games, g => secondSearch(g.game, g.categories), params);
console.log(r1, r2);
})();
或更正確的方法是使用更多代碼(因此,最后-第一個搜索不會等待):
(async () => {
const games = JSON.parse(JSON.stringify(req.body.games));
let params = { concurrency: 2};
let fns = [
...games.map(g => () => firstSearch(g.game, g.categories)),
...games.map(g => () => secondSearch(g.game, g.categories)),
];
let results = await Promise.map(fns, fn => fn(), params);
console.log(results);
})();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.