用于并行执行的 Flutter 多个异步方法

Max*_*lle 20 asynchronous async-await flutter

我仍然在为 async/await 模式而苦苦挣扎,所以我在这里问你一些精度。

我看到这个页面很好地解释了异步/等待模式。我在这里发布困扰我的例子:

import 'dart:async';

Future<String> firstAsync() async {
  await Future<String>.delayed(const Duration(seconds: 2));
  return "First!";
}

Future<String> secondAsync() async {
  await Future<String>.delayed(const Duration(seconds: 2));
  return "Second!";
}

Future<String> thirdAsync() async {
  await Future<String>.delayed(const Duration(seconds: 2));
  return "Third!";
}

void main() async {
  var f = await firstAsync();
  print(f);
  var s = await secondAsync();
  print(s);
  var t = await thirdAsync();
  print(t);
  print('done');
}
Run Code Online (Sandbox Code Playgroud)

在这个例子中,async一个接一个地调用每个方法,所以主函数的执行时间是 6 秒(3 x 2 秒)。但是,我不明白如果它们一个接一个地执行,异步函数有什么意义。

async功能不应该在后台执行?用并行async执行来固定流程难道不是多个功能的重点吗?

我想我在 flutter 中遗漏了一些关于异步函数和 async/await 模式的东西,所以如果你能解释我,我将不胜感激。

最好的事物

小智 59

使用 Future.wait() 等待多个 Future 完成 如果函数的执行顺序不重要,您可以使用 Future.wait()。

功能快速连续触发;当它们都完成一个值时,Future.wait() 返回一个新的 Future。这个 Future 以一个包含每个函数产生的值的列表来完成。

Future
    .wait([firstAsync(), secondAsync(), thirdAsyncC()])
    .then((List responses) => chooseBestResponse(responses))
    .catchError((e) => handleError(e));
Run Code Online (Sandbox Code Playgroud)

或使用异步/等待

try {
    List responses = await Future.wait([firstAsync(), secondAsync(), thirdAsyncC()]);
} catch (e) {
    handleError(e)
}
Run Code Online (Sandbox Code Playgroud)

如果任何被调用的函数以错误结束,则 Future.wait() 返回的 Future 也会以错误结束。使用 catchError() 来处理错误。

资源:https : //v1-dartlang-org.firebaseapp.com/tutorials/language/futures#waiting-on-multiple-futures-to-complete-using-futurewait


Afz*_*zal 16

如果有人遇到这个问题,请使用async. Dart 有一个名为 的函数FutureGroup。您可以使用它来并行运行 future。

样本:

final futureGroup = FutureGroup();//instantiate it

void runAllFutures() {
  /// add all the futures , this is not the best way u can create an extension method to add all at the same time
  futureGroup.add(hello());
  futureGroup.add(checkLocalAuth());
  futureGroup.add(hello1());
  futureGroup.add(hello2());
  futureGroup.add(hello3());
  
  // call the `.close` of the group to fire all the futures,
  // once u call `.close` this group cant be used again
  futureGroup.close();

  // await for future group to finish (all futures inside it to finish)
  await futureGroup.future;
}
Run Code Online (Sandbox Code Playgroud)

futureGroup有一些有用的方法可以帮助你。.future等等..检查文档以获取更多信息。

以下是使用示例,示例一使用await/async示例二使用Future.then

  • @MAfzal我使用谷歌的元组实现https://gist.github.com/marcellodesales/39857e464b38167f0631150ee6238943 ...谢谢! (3认同)
  • 对于一个不可避免的问题来说,这是一个很好的答案——运行多个异步调用而不关心它们的执行顺序,而是关心您实际上“等待”它们作为一个组完成。本质上是对 future 进行 __grouping__ 并等待它们作为一个整体执行。 (2认同)
  • @MarcellodeSales 你仍然可以通过“等待”“futureGroup.futures”获得他们的所有结果 (2认同)

xae*_*hos 11

该示例旨在展示如何在不实际阻塞线程的情况下等待长时间运行的进程。在实践中,如果您有几个想要并行运行(例如:独立的网络调用),您可以优化一些东西。

调用会await停止方法的执行,直到未来完成,所以调用secondAsync不会发生,直到firstAsync完成,依此类推。如果你这样做:

void main() async {
  var f = firstAsync();
  var s = secondAsync();
  var t = thirdAsync();
  print(await f);
  print(await s);
  print(await t);
  print('done');
}
Run Code Online (Sandbox Code Playgroud)

然后立即启动所有三个期货,然后您等待它们以特定顺序完成。

值得强调的是,现在fst有型Future<String>。您可以为每个未来尝试不同的持续时间,或更改语句的顺序。


Sha*_*han 7

你总是可以在一个未来中使用它们

final results = await Future.wait([
  firstAsync();
  secondAsync();
  thirdAsync();
]);
Run Code Online (Sandbox Code Playgroud)

结果将是您返回类型的数组。在本例中为字符串数组。

干杯。