在Dart中,如果我将Future.wait与Futures列表一起使用,并且其中一个Futures引发错误,那么其他Futures会发生什么? [英] In Dart, if I use Future.wait with a list of Futures and an error is thrown on one of the Futures, what happens to the other Futures?

查看:1052
本文介绍了在Dart中,如果我将Future.wait与Futures列表一起使用,并且其中一个Futures引发错误,那么其他Futures会发生什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有以下代码:

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 捕获的错误对未来的死有什么想法?还是保留哪些期货?

Does the error caught by catchError have any idea of what Future died? Or which Futures remain?

推荐答案

通过运行打印来确定打印的内容很容易(您没有Dart VM吗? ):

Determining what is printed is pretty easy by running it (do you not have a Dart VM handy?):


a
c
AsyncError: 'Error!'

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。错误是使用('错误!',在这种情况下)创建的值,因此将其设置为表示哪个Future具有错误,您可以看到哪个死亡。当然,如果您不是造成错误的人,那将无济于事。

e.error is the value that was created with ('Error!', in this case), so by setting that to something indicating which Future has the error, you can see which Future "died". Of course, if you're not the one creating the error, that doesn't help.

通常,我认为您使用 Future。在类似的列表上使用wait()时,将类似地处理其中的任何错误。需要知道哪一个失败可能表明您不想对所有这些都一起($ wait()。

In general, I think you use Future.wait() on a List like this when an error in any of them would be handled similarly. Needing to know which one failed might be a sign that you don't want to wait() on all of them together.

更新:我刚刚意识到问题标题问的是问题正文中未问的问题:其他期货会怎样?

Update: I just realized the question title asks a question not asked in the question body: What happens to the other Futures?

其他期货继续运行。 wait()返回的Future会在收到错误后立即抛出该错误,因此所有返回值都将丢失,并且如果其他Future抛出任何错误,它没有被捕获,但是每个Future仍然运行,直到返回或引发错误。

The other Futures keep running. The Future returned by wait() throws whichever error it receives as soon as it receives it, so all return values are lost, and if any of the other Futures throws an error, it isn't caught, but each Future still runs until returning or throwing an error.

这篇关于在Dart中,如果我将Future.wait与Futures列表一起使用,并且其中一个Futures引发错误,那么其他Futures会发生什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆