等待多种地图方法以使用promise返回,然后获取所有地图的返回值

时间:2018-10-21 14:09:16

标签: javascript node.js express promise bluebird

在一个快递项目中,我有2个映射,它们都通过一个操纵up实例运行,并且都返回数组。当前,我正在使用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`
  });

2 个答案:

答案 0 :(得分:3)

Promise.all接受Promises数组作为参数。您需要将两个数组作为单个数组参数传递

return Promise.all(f.concat(s))
  .then(function(g) {
    console.log(g); //only returns `f` result, not the `s`
  });

答案 1 :(得分:1)

不需要使用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);
 })();