代码之家  ›  专栏  ›  技术社区  ›  Igor F.

如何根据产生期货的期货在Dart中分配期货结果?

  •  0
  • Igor F.  · 技术社区  · 7 年前

    在Dart中,我想运行几个彼此独立的代价高昂的函数,并根据生成它们的函数将结果分配给我的变量。这大致是一个并行版本:

    double x = getX();
    double y = getY();
    

    我在想这样的事情:

    double x, y;
    Future.wait([
      futureGetX(),
      futureGetY()
    ]).then((List results) {
      results.foreach((r) {
        // if(r is produced by futureGetX) x = r;
        // if(r is produced by futureGetY) y = r;
      }); 
    });
    

    我不知道该怎么实现 is produced by then 第二部分,检查结果的类别:

    if(r is wrapperForX) x = r.getValue();
    if(r is wrapperForY) y = r.getValue();
    

    但这对我来说似乎很不雅。有什么建议吗?

    4 回复  |  直到 7 年前
        1
  •  1
  •   Randal Schwartz    7 年前

    未经测试,但我想我得到了这个

    使用封口:

    Future.wait([
      () => { x = await futureGetX()},
      () => { y = await futureGetY()},
    ]);
    
        2
  •  0
  •   Igor F.    7 年前

    多亏了Randal,我找到了一个解决方案:

    Future.wait([
      () async { x = await futureGetX(); } (),
      () async { y = await futureGetY(); } ()
    ]);
    
        3
  •  0
  •   lrn    7 年前

    为了并行等待未来,您可以使用 Future.wait 列表中的结果由返回(异步) 将来等待 都在 因为期货是原始的,所以不用 forEach 你可以做:

    x = results[0];
    y = results[1];
    
        4
  •  0
  •   Dafe Å imonek    7 年前

    另一种方法是使用异步包中的FutureGroup,记录结果列表的FIFO行为: https://www.dartdocs.org/documentation/async/1.13.3/async/FutureGroup-class.html