Flutter FutureOr and Future<

2019-10-15  本文已影响0人  LXJDBXJ

以下为翻译加理解

FutureOr<T>

  1. Future<S> then<S>(FutureOr<S> f(T x), ...)
    Future<T>.then 函数 takes a callback [f] 然后返回 S或者一个 Future<S>.
  2. void complete(FutureOr<T> value)
    Completer<T>.complete takes either a T or Future<T>.
  1. 子类型(sub-type) 因为 Object 是union 的类型之一,
  2. 超类型(super-type) 因为 Object 是两种联合类型的超类型。
  3. 合在一起的就是FutureOr<Object>同样等于 Object.
  4. 所以可以推论,“futureor<object>” 等于futureor<futureor<object>>futureor<future<object>>等于Future<Object>

理解了FutureOr<T> 接下来就可以真正的入手 Future<T>

Future<T>

[Future] 可以通过两种方式完成:

  1. 有value的(“Future成功”)。
  2. 或error误(“Future失败”)。
    用户可以为每种情况设置回调。

在某些情况下,我们说一个future与另一个future一起完成。这是一个很短的表达future的方法,说明future是以同样的方式完成的,具有相同的值或错误,
当另一个future完成的时候。只要核心库中的某个函数可以完成future(例如[completer.complete]或[new future.value]),然后它也接受另一个future,并为开发人员做这项工作。
注册一对回调的结果是一个新的Future “successor”),然后通过调用相应的回调。如果调用的回调throws,则后续任务将完成,但会出现错误
For example

   Future<int> successor = future.then((int value) {
  // Invoked when the future is completed with a value.
    return 42;  // The successor is completed with the value 42.
  },
  onError: (e) {
     // Invoked when the future is completed with an error.
      if (canHandle(e)) {
    return 499;  // The successor is completed with the value 499.
  } else {
      throw e;  // The successor is completed with the error e.
    }
  });

如果一个future在它以错误结束时没有后继者,它将错误消息转发到全局错误处理程序。此行为确保不会自动删除任何错误。但是,这也意味着应该尽早安装错误处理程序,使它们在一个有错误的未来一结束就存在。下面的示例演示了这个潜在的bug:

 var future = getFuture();
new Timer(new Duration(milliseconds: 5), () {
  // The error-handler is not attached until 5 ms after the future has
  // been received. If the future fails before that, the error is
  // forwarded to the global error-handler, even though there is code
  // (just below) to eventually handle the error.
  future.then((value) { useValue(value); },
              onError: (e) { handleError(e); });
 });

注册回调时,注册这两个回调通常更容易阅读。通过首先对一个参数使用[then]分别回调(值处理程序)并使用第二个[catchError]来处理错误。每一个都会转发他们无法处理的结果对于他们的继任者,他们一起处理价值和错误结果。它还具有处理[then]值回调。使用顺序处理程序而不是并行处理程序通常会导致更容易推理。它还使异步代码非常类似于同步代码:

 // Synchronous code.
try {
  int value = foo();
   return bar(value);
} catch (e) {
   return 499;
 }

基于 futures:等于异步代码:

Future<int> future = new Future(foo); 
// Result of foo() as a future.
future.then((int value) => bar(value))
      .catchError((e) => 499);

与同步代码类似,错误处理程序(注册于[catchError])正在处理由“foo”或“bar”引发的任何错误。如果错误处理程序已注册为的“onerror”参数,在“then”调用中,它不会从“bar”调用中catch errors。Futures可以注册多个回调对。每个继任者都是独立处理,并被当作唯一的继承人处理。future也可能永远无法完成。在这种情况下,没有回调被调用。

后期会贴上相关的高级用法,如有疑问?:请在下方评论区写下 或者加入qq社区,QQ讨论群 719918895

上一篇 下一篇

猜你喜欢

热点阅读