gpt4 book ai didi

dart - 在 Dart 中,如果我将 Future.wait 与 Futures 列表一起使用,并且在其中一个 Futures 上抛出错误,那么其他 Futures 会发生什么?

转载 作者:行者123 更新时间:2023-12-04 17:36:51 27 4
gpt4 key购买 nike

如果我有以下代码:

Future<int> a = new Future(() { print('a'); return 1; });
Future<int> b = new Future.error('Error!');
Future<int> c = new Future(() { print('c'); return 3; });

Future.wait([a, b, c])
.then((List<int> values) => print(values))
.catchError((e) => print(e));

打印什么?

是否由 catchError 捕获的错误知道 future 死了什么吗?或者还有哪些 future ?

最佳答案

通过运行它可以很容易地确定打印的内容(你手头没有 Dart VM 吗?):

一种
C
异步错误:'错误!'

documentation for Future.wait()说:

Wait for all the given futures to complete and collect their values.

Returns a future which will complete once all the futures in a list are complete. If any of the futures in the list completes with an error, the resulting future also completes with an error. Otherwise the value of the returned future will be a list of all the values that were produced.


e.error是使用( 'Error!' ,在这种情况下)创建的值,因此通过将其设置为指示哪个 Future 有错误的内容,您可以看到哪个 Future “死了”。当然,如果您不是造成错误的人,那也无济于事。

一般来说,我认为你使用 Future.wait()在像这样的列表中,当其中任何一个中的错误将被类似地处理时。需要知道哪个失败可能表明您不想这样做 wait()在他们所有人在一起。

更新:我刚刚意识到问题标题提出了一个问题正文中没有提出的问题:其他 future 会发生什么?

其他 future 继续运行。由 wait() 返回的 future 收到它后立即抛出它收到的任何错误,因此所有返回值都将丢失,并且如果任何其他 Futures 抛出错误,则不会被捕获,但每个 Future 仍会运行,直到返回或抛出错误。

关于dart - 在 Dart 中,如果我将 Future.wait 与 Futures 列表一起使用,并且在其中一个 Futures 上抛出错误,那么其他 Futures 会发生什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16022601/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com