【问题标题】:Waiting on multiple map methods to return using promises and then get all maps return values等待多个map方法使用promise返回,然后获取所有map返回值
【发布时间】:2019-03-25 18:00:44
【问题描述】:

在一个 express 项目中,我有 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`
  });

【问题讨论】:

    标签: javascript node.js express promise bluebird


    【解决方案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);
     })();
    

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

      • 嗯,有道理,谢谢,这按预期工作!
      • 很高兴能帮上忙
      猜你喜欢
      • 1970-01-01
      • 2013-09-18
      • 2017-02-10
      • 2019-12-08
      • 2016-09-15
      • 2012-04-07
      • 2019-05-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多