使用承诺等待 return 的多个映射方法,然后获取所有映射 return 值
Waiting on multiple map methods to return using promises and then get all maps return values
在一个 express 项目中,我有 2 个地图,它们都 运行 通过一个 puppeteer 实例和两个 return 数组。目前,我正在使用 Promise.all 等待两个地图完成,但它只 returns 来自第一个数组而不是第二个数组的值。我该怎么做才能获得两个地图变量结果?
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);
})();
在一个 express 项目中,我有 2 个地图,它们都 运行 通过一个 puppeteer 实例和两个 return 数组。目前,我正在使用 Promise.all 等待两个地图完成,但它只 returns 来自第一个数组而不是第二个数组的值。我该怎么做才能获得两个地图变量结果?
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);
})();