| OLD | NEW |
| (Empty) |
| 1 // Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file | |
| 2 // for details. All rights reserved. Use of this source code is governed by a | |
| 3 // BSD-style license that can be found in the LICENSE file. | |
| 4 | |
| 5 part of dart.async; | |
| 6 | |
| 7 /// A type representing values that are either `Future<T>` or `T`. | |
| 8 /// | |
| 9 /// This class declaration is a public stand-in for an internal | |
| 10 /// future-or-value generic type. References to this class are resolved to the | |
| 11 /// internal type. | |
| 12 /// | |
| 13 /// It is a compile-time error for any class to extend, mix in or implement | |
| 14 /// `FutureOr`. | |
| 15 /// | |
| 16 /// Note: the `FutureOr<T>` type is interpreted as `dynamic` in non strong-mode. | |
| 17 /// | |
| 18 /// # Examples | |
| 19 /// ``` dart | |
| 20 /// // The `Future<T>.then` function takes a callback [f] that returns either | |
| 21 /// // an `S` or a `Future<S>`. | |
| 22 /// Future<S> then<S>(FutureOr<S> f(T x), ...); | |
| 23 /// | |
| 24 /// // `Completer<T>.complete` takes either a `T` or `Future<T>`. | |
| 25 /// void complete(FutureOr<T> value); | |
| 26 /// ``` | |
| 27 /// | |
| 28 /// # Advanced | |
| 29 /// The `FutureOr<int>` type is actually the "type union" of the types `int` and | |
| 30 /// `Future<int>`. This type union is defined in such a way that | |
| 31 /// `FutureOr<Object>` is both a super- and sub-type of `Object` (sub-type | |
| 32 /// because `Object` is one of the types of the union, super-type because | |
| 33 /// `Object` is a super-type of both of the types of the union). Together it | |
| 34 /// means that `FutureOr<Object>` is equivalent to `Object`. | |
| 35 /// | |
| 36 /// As a corollary, `FutureOr<Object>` is equivalent to | |
| 37 /// `FutureOr<FutureOr<Object>>`, `FutureOr<Future<Object>> is equivalent to | |
| 38 /// `Future<Object>`. | |
| 39 abstract class FutureOr<T> { | |
| 40 // Private constructor, so that it is not subclassable, mixable, or | |
| 41 // instantiable. | |
| 42 FutureOr._() { | |
| 43 throw new UnsupportedError("FutureOr can't be instantiated"); | |
| 44 } | |
| 45 } | |
| 46 | |
| 47 /** | |
| 48 * An object representing a delayed computation. | |
| 49 * | |
| 50 * A [Future] is used to represent a potential value, or error, | |
| 51 * that will be available at some time in the future. | |
| 52 * Receivers of a [Future] can register callbacks | |
| 53 * that handle the value or error once it is available. | |
| 54 * For example: | |
| 55 * | |
| 56 * Future<int> future = getFuture(); | |
| 57 * future.then((value) => handleValue(value)) | |
| 58 * .catchError((error) => handleError(error)); | |
| 59 * | |
| 60 * A [Future] can complete in two ways: | |
| 61 * with a value ("the future succeeds") | |
| 62 * or with an error ("the future fails"). | |
| 63 * Users can install callbacks for each case. | |
| 64 * The result of registering a pair of callbacks is a new Future (the | |
| 65 * "successor") which in turn is completed with the result of invoking the | |
| 66 * corresponding callback. | |
| 67 * The successor is completed with an error if the invoked callback throws. | |
| 68 * For example: | |
| 69 * | |
| 70 * Future<int> successor = future.then((int value) { | |
| 71 * // Invoked when the future is completed with a value. | |
| 72 * return 42; // The successor is completed with the value 42. | |
| 73 * }, | |
| 74 * onError: (e) { | |
| 75 * // Invoked when the future is completed with an error. | |
| 76 * if (canHandle(e)) { | |
| 77 * return 499; // The successor is completed with the value 499. | |
| 78 * } else { | |
| 79 * throw e; // The successor is completed with the error e. | |
| 80 * } | |
| 81 * }); | |
| 82 * | |
| 83 * If a future does not have a successor when it completes with an error, | |
| 84 * it forwards the error message to the global error-handler. | |
| 85 * This behavior makes sure that no error is silently dropped. | |
| 86 * However, it also means that error handlers should be installed early, | |
| 87 * so that they are present as soon as a future is completed with an error. | |
| 88 * The following example demonstrates this potential bug: | |
| 89 * | |
| 90 * var future = getFuture(); | |
| 91 * new Timer(new Duration(milliseconds: 5), () { | |
| 92 * // The error-handler is not attached until 5 ms after the future has | |
| 93 * // been received. If the future fails before that, the error is | |
| 94 * // forwarded to the global error-handler, even though there is code | |
| 95 * // (just below) to eventually handle the error. | |
| 96 * future.then((value) { useValue(value); }, | |
| 97 * onError: (e) { handleError(e); }); | |
| 98 * }); | |
| 99 * | |
| 100 * When registering callbacks, it's often more readable to register the two | |
| 101 * callbacks separately, by first using [then] with one argument | |
| 102 * (the value handler) and using a second [catchError] for handling errors. | |
| 103 * Each of these will forward the result that they don't handle | |
| 104 * to their successors, and together they handle both value and error result. | |
| 105 * It also has the additional benefit of the [catchError] handling errors in the | |
| 106 * [then] value callback too. | |
| 107 * Using sequential handlers instead of parallel ones often leads to code that | |
| 108 * is easier to reason about. | |
| 109 * It also makes asynchronous code very similar to synchronous code: | |
| 110 * | |
| 111 * // Synchronous code. | |
| 112 * try { | |
| 113 * int value = foo(); | |
| 114 * return bar(value); | |
| 115 * } catch (e) { | |
| 116 * return 499; | |
| 117 * } | |
| 118 * | |
| 119 * Equivalent asynchronous code, based on futures: | |
| 120 * | |
| 121 * Future<int> future = new Future(foo); // Result of foo() as a future. | |
| 122 * future.then((int value) => bar(value)) | |
| 123 * .catchError((e) => 499); | |
| 124 * | |
| 125 * Similar to the synchronous code, the error handler (registered with | |
| 126 * [catchError]) is handling any errors thrown by either `foo` or `bar`. | |
| 127 * If the error-handler had been registered as the `onError` parameter of | |
| 128 * the `then` call, it would not catch errors from the `bar` call. | |
| 129 * | |
| 130 * Futures can have more than one callback-pair registered. Each successor is | |
| 131 * treated independently and is handled as if it was the only successor. | |
| 132 * | |
| 133 * A future may also fail to ever complete. In that case, no callbacks are | |
| 134 * called. | |
| 135 */ | |
| 136 abstract class Future<T> { | |
| 137 // The `_nullFuture` is a completed Future with the value `null`. | |
| 138 static final _Future _nullFuture = new Future.value(null); | |
| 139 | |
| 140 /** | |
| 141 * Creates a future containing the result of calling [computation] | |
| 142 * asynchronously with [Timer.run]. | |
| 143 * | |
| 144 * If the result of executing [computation] throws, the returned future is | |
| 145 * completed with the error. | |
| 146 * | |
| 147 * If the returned value is itself a [Future], completion of | |
| 148 * the created future will wait until the returned future completes, | |
| 149 * and will then complete with the same result. | |
| 150 * | |
| 151 * If a non-future value is returned, the returned future is completed | |
| 152 * with that value. | |
| 153 */ | |
| 154 factory Future(computation()) { | |
| 155 _Future<T> result = new _Future<T>(); | |
| 156 Timer.run(() { | |
| 157 try { | |
| 158 result._complete(computation()); | |
| 159 } catch (e, s) { | |
| 160 _completeWithErrorCallback(result, e, s); | |
| 161 } | |
| 162 }); | |
| 163 return result; | |
| 164 } | |
| 165 | |
| 166 /** | |
| 167 * Creates a future containing the result of calling [computation] | |
| 168 * asynchronously with [scheduleMicrotask]. | |
| 169 * | |
| 170 * If executing [computation] throws, | |
| 171 * the returned future is completed with the thrown error. | |
| 172 * | |
| 173 * If calling [computation] returns a [Future], completion of | |
| 174 * the created future will wait until the returned future completes, | |
| 175 * and will then complete with the same result. | |
| 176 * | |
| 177 * If calling [computation] returns a non-future value, | |
| 178 * the returned future is completed with that value. | |
| 179 */ | |
| 180 factory Future.microtask(computation()) { | |
| 181 _Future<T> result = new _Future<T>(); | |
| 182 scheduleMicrotask(() { | |
| 183 try { | |
| 184 result._complete(computation()); | |
| 185 } catch (e, s) { | |
| 186 _completeWithErrorCallback(result, e, s); | |
| 187 } | |
| 188 }); | |
| 189 return result; | |
| 190 } | |
| 191 | |
| 192 /** | |
| 193 * Creates a future containing the result of immediately calling | |
| 194 * [computation]. | |
| 195 * | |
| 196 * If calling [computation] throws, the returned future is completed with the | |
| 197 * error. | |
| 198 * | |
| 199 * If calling [computation] returns a [Future], completion of | |
| 200 * the created future will wait until the returned future completes, | |
| 201 * and will then complete with the same result. | |
| 202 * | |
| 203 * If calling [computation] returns a non-future value, | |
| 204 * the returned future is completed with that value. | |
| 205 */ | |
| 206 factory Future.sync(computation()) { | |
| 207 try { | |
| 208 var result = computation(); | |
| 209 return new Future<T>.value(result); | |
| 210 } catch (error, stackTrace) { | |
| 211 return new Future<T>.error(error, stackTrace); | |
| 212 } | |
| 213 } | |
| 214 | |
| 215 /** | |
| 216 * A future whose value is available in the next event-loop iteration. | |
| 217 * | |
| 218 * If [value] is not a [Future], using this constructor is equivalent | |
| 219 * to [:new Future<T>.sync(() => value):]. | |
| 220 * | |
| 221 * Use [Completer] to create a Future and complete it later. | |
| 222 */ | |
| 223 factory Future.value([value]) { | |
| 224 return new _Future<T>.immediate(value); | |
| 225 } | |
| 226 | |
| 227 /** | |
| 228 * A future that completes with an error in the next event-loop iteration. | |
| 229 * | |
| 230 * If [error] is `null`, it is replaced by a [NullThrownError]. | |
| 231 * | |
| 232 * Use [Completer] to create a future and complete it later. | |
| 233 */ | |
| 234 factory Future.error(Object error, [StackTrace stackTrace]) { | |
| 235 error = _nonNullError(error); | |
| 236 if (!identical(Zone.current, _ROOT_ZONE)) { | |
| 237 AsyncError replacement = Zone.current.errorCallback(error, stackTrace); | |
| 238 if (replacement != null) { | |
| 239 error = _nonNullError(replacement.error); | |
| 240 stackTrace = replacement.stackTrace; | |
| 241 } | |
| 242 } | |
| 243 return new _Future<T>.immediateError(error, stackTrace); | |
| 244 } | |
| 245 | |
| 246 /** | |
| 247 * Creates a future that runs its computation after a delay. | |
| 248 * | |
| 249 * The [computation] will be executed after the given [duration] has passed, | |
| 250 * and the future is completed with the result. | |
| 251 * If the duration is 0 or less, | |
| 252 * it completes no sooner than in the next event-loop iteration. | |
| 253 * | |
| 254 * If [computation] is omitted, | |
| 255 * it will be treated as if [computation] was set to `() => null`, | |
| 256 * and the future will eventually complete with the `null` value. | |
| 257 * | |
| 258 * If calling [computation] throws, the created future will complete with the | |
| 259 * error. | |
| 260 * | |
| 261 * See also [Completer] for a way to create and complete a future at a | |
| 262 * later time that isn't necessarily after a known fixed duration. | |
| 263 */ | |
| 264 factory Future.delayed(Duration duration, [computation()]) { | |
| 265 _Future<T> result = new _Future<T>(); | |
| 266 new Timer(duration, () { | |
| 267 try { | |
| 268 result._complete(computation?.call()); | |
| 269 } catch (e, s) { | |
| 270 _completeWithErrorCallback(result, e, s); | |
| 271 } | |
| 272 }); | |
| 273 return result; | |
| 274 } | |
| 275 | |
| 276 /** | |
| 277 * Wait for all the given futures to complete and collect their values. | |
| 278 * | |
| 279 * Returns a future which will complete once all the futures in a list are | |
| 280 * complete. If any of the futures in the list completes with an error, | |
| 281 * the resulting future also completes with an error. Otherwise the value | |
| 282 * of the returned future will be a list of all the values that were | |
| 283 * produced. | |
| 284 * | |
| 285 * If `eagerError` is true, the future completes with an error immediately on | |
| 286 * the first error from one of the futures. Otherwise all futures must | |
| 287 * complete before the returned future is completed (still with the first | |
| 288 * error to occur, the remaining errors are silently dropped). | |
| 289 * | |
| 290 * If [cleanUp] is provided, in the case of an error, any non-null result of | |
| 291 * a successful future is passed to `cleanUp`, which can then release any | |
| 292 * resources that the successful operation allocated. | |
| 293 * | |
| 294 * The call to `cleanUp` should not throw. If it does, the error will be an | |
| 295 * uncaught asynchronous error. | |
| 296 */ | |
| 297 static Future<List<T>> wait<T>(Iterable<Future<T>> futures, | |
| 298 {bool eagerError: false, | |
| 299 void cleanUp(T successValue)}) { | |
| 300 final _Future<List<T>> result = new _Future<List<T>>(); | |
| 301 List<T> values; // Collects the values. Set to null on error. | |
| 302 int remaining = 0; // How many futures are we waiting for. | |
| 303 var error; // The first error from a future. | |
| 304 StackTrace stackTrace; // The stackTrace that came with the error. | |
| 305 | |
| 306 // Handle an error from any of the futures. | |
| 307 void handleError(theError, theStackTrace) { | |
| 308 remaining--; | |
| 309 if (values != null) { | |
| 310 if (cleanUp != null) { | |
| 311 for (var value in values) { | |
| 312 if (value != null) { | |
| 313 // Ensure errors from cleanUp are uncaught. | |
| 314 new Future.sync(() { cleanUp(value); }); | |
| 315 } | |
| 316 } | |
| 317 } | |
| 318 values = null; | |
| 319 if (remaining == 0 || eagerError) { | |
| 320 result._completeError(theError, theStackTrace); | |
| 321 } else { | |
| 322 error = theError; | |
| 323 stackTrace = theStackTrace; | |
| 324 } | |
| 325 } else if (remaining == 0 && !eagerError) { | |
| 326 result._completeError(error, stackTrace); | |
| 327 } | |
| 328 } | |
| 329 | |
| 330 try { | |
| 331 // As each future completes, put its value into the corresponding | |
| 332 // position in the list of values. | |
| 333 for (Future future in futures) { | |
| 334 int pos = remaining; | |
| 335 future.then((T value) { | |
| 336 remaining--; | |
| 337 if (values != null) { | |
| 338 values[pos] = value; | |
| 339 if (remaining == 0) { | |
| 340 result._completeWithValue(values); | |
| 341 } | |
| 342 } else { | |
| 343 if (cleanUp != null && value != null) { | |
| 344 // Ensure errors from cleanUp are uncaught. | |
| 345 new Future.sync(() { cleanUp(value); }); | |
| 346 } | |
| 347 if (remaining == 0 && !eagerError) { | |
| 348 result._completeError(error, stackTrace); | |
| 349 } | |
| 350 } | |
| 351 }, onError: handleError); | |
| 352 // Increment the 'remaining' after the call to 'then'. | |
| 353 // If that call throws, we don't expect any future callback from | |
| 354 // the future, and we also don't increment remaining. | |
| 355 remaining++; | |
| 356 } | |
| 357 if (remaining == 0) { | |
| 358 return new Future.value(const []); | |
| 359 } | |
| 360 values = new List<T>(remaining); | |
| 361 } catch (e, st) { | |
| 362 // The error must have been thrown while iterating over the futures | |
| 363 // list, or while installing a callback handler on the future. | |
| 364 if (remaining == 0 || eagerError) { | |
| 365 // Throw a new Future.error. | |
| 366 // Don't just call `result._completeError` since that would propagate | |
| 367 // the error too eagerly, not giving the callers time to install | |
| 368 // error handlers. | |
| 369 // Also, don't use `_asyncCompleteError` since that one doesn't give | |
| 370 // zones the chance to intercept the error. | |
| 371 return new Future.error(e, st); | |
| 372 } else { | |
| 373 // Don't allocate a list for values, thus indicating that there was an | |
| 374 // error. | |
| 375 // Set error to the caught exception. | |
| 376 error = e; | |
| 377 stackTrace = st; | |
| 378 } | |
| 379 } | |
| 380 return result; | |
| 381 } | |
| 382 | |
| 383 /** | |
| 384 * Returns the result of the first future in [futures] to complete. | |
| 385 * | |
| 386 * The returned future is completed with the result of the first | |
| 387 * future in [futures] to report that it is complete. | |
| 388 * The results of all the other futures are discarded. | |
| 389 * | |
| 390 * If [futures] is empty, or if none of its futures complete, | |
| 391 * the returned future never completes. | |
| 392 */ | |
| 393 static Future<T> any<T>(Iterable<Future<T>> futures) { | |
| 394 var completer = new Completer<T>.sync(); | |
| 395 var onValue = (T value) { | |
| 396 if (!completer.isCompleted) completer.complete(value); | |
| 397 }; | |
| 398 var onError = (error, stack) { | |
| 399 if (!completer.isCompleted) completer.completeError(error, stack); | |
| 400 }; | |
| 401 for (var future in futures) { | |
| 402 future.then(onValue, onError: onError); | |
| 403 } | |
| 404 return completer.future; | |
| 405 } | |
| 406 | |
| 407 | |
| 408 /** | |
| 409 * Perform an async operation for each element of the iterable, in turn. | |
| 410 * | |
| 411 * Runs [f] for each element in [input] in order, moving to the next element | |
| 412 * only when the [Future] returned by [f] completes. Returns a [Future] that | |
| 413 * completes when all elements have been processed. | |
| 414 * | |
| 415 * The return values of all [Future]s are discarded. Any errors will cause the | |
| 416 * iteration to stop and will be piped through the returned [Future]. | |
| 417 * | |
| 418 * If [f] returns a non-[Future], iteration continues immediately. Otherwise | |
| 419 * it waits for the returned [Future] to complete. | |
| 420 */ | |
| 421 static Future forEach<T>(Iterable<T> input, f(T element)) { | |
| 422 var iterator = input.iterator; | |
| 423 return doWhile(() { | |
| 424 if (!iterator.moveNext()) return false; | |
| 425 return new Future.sync(() => f(iterator.current)).then((_) => true); | |
| 426 }); | |
| 427 } | |
| 428 | |
| 429 /** | |
| 430 * Performs an async operation repeatedly until it returns `false`. | |
| 431 * | |
| 432 * The function [f] is called repeatedly while it returns either the [bool] | |
| 433 * value `true` or a [Future] which completes with the value `true`. | |
| 434 * | |
| 435 * If a call to [f] returns `false` or a [Future] that completes to `false`, | |
| 436 * iteration ends and the future returned by [doWhile] is completed. | |
| 437 * | |
| 438 * If a future returned by [f] completes with an error, iteration ends and | |
| 439 * the future returned by [doWhile] completes with the same error. | |
| 440 * | |
| 441 * The [f] function must return either a `bool` value or a [Future] completing | |
| 442 * with a `bool` value. | |
| 443 */ | |
| 444 static Future doWhile(f()) { | |
| 445 _Future doneSignal = new _Future(); | |
| 446 var nextIteration; | |
| 447 // Bind this callback explicitly so that each iteration isn't bound in the | |
| 448 // context of all the previous iterations' callbacks. | |
| 449 nextIteration = Zone.current.bindUnaryCallback((bool keepGoing) { | |
| 450 if (keepGoing) { | |
| 451 new Future.sync(f).then(nextIteration, | |
| 452 onError: doneSignal._completeError); | |
| 453 } else { | |
| 454 doneSignal._complete(null); | |
| 455 } | |
| 456 }, runGuarded: true); | |
| 457 nextIteration(true); | |
| 458 return doneSignal; | |
| 459 } | |
| 460 | |
| 461 /** | |
| 462 * Register callbacks to be called when this future completes. | |
| 463 * | |
| 464 * When this future completes with a value, | |
| 465 * the [onValue] callback will be called with that value. | |
| 466 * If this future is already completed, the callback will not be called | |
| 467 * immediately, but will be scheduled in a later microtask. | |
| 468 * | |
| 469 * If [onError] is provided, and this future completes with an error, | |
| 470 * the `onError` callback is called with that error and its stack trace. | |
| 471 * The `onError` callback must accept either one argument or two arguments. | |
| 472 * If `onError` accepts two arguments, | |
| 473 * it is called with both the error and the stack trace, | |
| 474 * otherwise it is called with just the error object. | |
| 475 * | |
| 476 * Returns a new [Future] | |
| 477 * which is completed with the result of the call to `onValue` | |
| 478 * (if this future completes with a value) | |
| 479 * or to `onError` (if this future completes with an error). | |
| 480 * | |
| 481 * If the invoked callback throws, | |
| 482 * the returned future is completed with the thrown error | |
| 483 * and a stack trace for the error. | |
| 484 * In the case of `onError`, | |
| 485 * if the exception thrown is `identical` to the error argument to `onError`, | |
| 486 * the throw is considered a rethrow, | |
| 487 * and the original stack trace is used instead. | |
| 488 * | |
| 489 * If the callback returns a [Future], | |
| 490 * the future returned by `then` will be completed with | |
| 491 * the same result as the future returned by the callback. | |
| 492 * | |
| 493 * If [onError] is not given, and this future completes with an error, | |
| 494 * the error is forwarded directly to the returned future. | |
| 495 * | |
| 496 * In most cases, it is more readable to use [catchError] separately, possibly | |
| 497 * with a `test` parameter, instead of handling both value and error in a | |
| 498 * single [then] call. | |
| 499 */ | |
| 500 Future<S> then<S>(FutureOr<S> onValue(T value), { Function onError }); | |
| 501 | |
| 502 /** | |
| 503 * Handles errors emitted by this [Future]. | |
| 504 * | |
| 505 * This is the asynchronous equivalent of a "catch" block. | |
| 506 * | |
| 507 * Returns a new [Future] that will be completed with either the result of | |
| 508 * this future or the result of calling the `onError` callback. | |
| 509 * | |
| 510 * If this future completes with a value, | |
| 511 * the returned future completes with the same value. | |
| 512 * | |
| 513 * If this future completes with an error, | |
| 514 * then [test] is first called with the error value. | |
| 515 * | |
| 516 * If `test` returns false, the exception is not handled by this `catchError`, | |
| 517 * and the returned future completes with the same error and stack trace | |
| 518 * as this future. | |
| 519 * | |
| 520 * If `test` returns `true`, | |
| 521 * [onError] is called with the error and possibly stack trace, | |
| 522 * and the returned future is completed with the result of this call | |
| 523 * in exactly the same way as for [then]'s `onError`. | |
| 524 * | |
| 525 * If `test` is omitted, it defaults to a function that always returns true. | |
| 526 * The `test` function should not throw, but if it does, it is handled as | |
| 527 * if the `onError` function had thrown. | |
| 528 * | |
| 529 * Example: | |
| 530 * | |
| 531 * foo | |
| 532 * .catchError(..., test: (e) => e is ArgumentError) | |
| 533 * .catchError(..., test: (e) => e is NoSuchMethodError) | |
| 534 * .then((v) { ... }); | |
| 535 * | |
| 536 * This method is equivalent to: | |
| 537 * | |
| 538 * Future catchError(onError(error), | |
| 539 * {bool test(error)}) { | |
| 540 * this.then((v) => v, // Forward the value. | |
| 541 * // But handle errors, if the [test] succeeds. | |
| 542 * onError: (e, stackTrace) { | |
| 543 * if (test == null || test(e)) { | |
| 544 * if (onError is ZoneBinaryCallback) { | |
| 545 * return onError(e, stackTrace); | |
| 546 * } | |
| 547 * return onError(e); | |
| 548 * } | |
| 549 * throw e; | |
| 550 * }); | |
| 551 * } | |
| 552 * | |
| 553 */ | |
| 554 // The `Function` below can stand for several types: | |
| 555 // - (dynamic) -> T | |
| 556 // - (dynamic, StackTrace) -> T | |
| 557 // - (dynamic) -> Future<T> | |
| 558 // - (dynamic, StackTrace) -> Future<T> | |
| 559 // Given that there is a `test` function that is usually used to do an | |
| 560 // `isCheck` we should also expect functions that take a specific argument. | |
| 561 // Note: making `catchError` return a `Future<T>` in non-strong mode could be | |
| 562 // a breaking change. | |
| 563 Future<T> catchError(Function onError, | |
| 564 {bool test(Object error)}); | |
| 565 | |
| 566 /** | |
| 567 * Register a function to be called when this future completes. | |
| 568 * | |
| 569 * The [action] function is called when this future completes, whether it | |
| 570 * does so with a value or with an error. | |
| 571 * | |
| 572 * This is the asynchronous equivalent of a "finally" block. | |
| 573 * | |
| 574 * The future returned by this call, `f`, will complete the same way | |
| 575 * as this future unless an error occurs in the [action] call, or in | |
| 576 * a [Future] returned by the [action] call. If the call to [action] | |
| 577 * does not return a future, its return value is ignored. | |
| 578 * | |
| 579 * If the call to [action] throws, then `f` is completed with the | |
| 580 * thrown error. | |
| 581 * | |
| 582 * If the call to [action] returns a [Future], `f2`, then completion of | |
| 583 * `f` is delayed until `f2` completes. If `f2` completes with | |
| 584 * an error, that will be the result of `f` too. The value of `f2` is always | |
| 585 * ignored. | |
| 586 * | |
| 587 * This method is equivalent to: | |
| 588 * | |
| 589 * Future<T> whenComplete(action()) { | |
| 590 * return this.then((v) { | |
| 591 * var f2 = action(); | |
| 592 * if (f2 is Future) return f2.then((_) => v); | |
| 593 * return v | |
| 594 * }, onError: (e) { | |
| 595 * var f2 = action(); | |
| 596 * if (f2 is Future) return f2.then((_) { throw e; }); | |
| 597 * throw e; | |
| 598 * }); | |
| 599 * } | |
| 600 */ | |
| 601 Future<T> whenComplete(action()); | |
| 602 | |
| 603 /** | |
| 604 * Creates a [Stream] containing the result of this future. | |
| 605 * | |
| 606 * The stream will produce single data or error event containing the | |
| 607 * completion result of this future, and then it will close with a | |
| 608 * done event. | |
| 609 * | |
| 610 * If the future never completes, the stream will not produce any events. | |
| 611 */ | |
| 612 Stream<T> asStream(); | |
| 613 | |
| 614 /** | |
| 615 * Time-out the future computation after [timeLimit] has passed. | |
| 616 * | |
| 617 * Returns a new future that completes with the same value as this future, | |
| 618 * if this future completes in time. | |
| 619 * | |
| 620 * If this future does not complete before `timeLimit` has passed, | |
| 621 * the [onTimeout] action is executed instead, and its result (whether it | |
| 622 * returns or throws) is used as the result of the returned future. | |
| 623 * The [onTimeout] function must return a [T] or a `Future<T>`. | |
| 624 * | |
| 625 * If `onTimeout` is omitted, a timeout will cause the returned future to | |
| 626 * complete with a [TimeoutException]. | |
| 627 */ | |
| 628 Future<T> timeout(Duration timeLimit, {onTimeout()}); | |
| 629 } | |
| 630 | |
| 631 /** | |
| 632 * Thrown when a scheduled timeout happens while waiting for an async result. | |
| 633 */ | |
| 634 class TimeoutException implements Exception { | |
| 635 /** Description of the cause of the timeout. */ | |
| 636 final String message; | |
| 637 /** The duration that was exceeded. */ | |
| 638 final Duration duration; | |
| 639 | |
| 640 TimeoutException(this.message, [this.duration]); | |
| 641 | |
| 642 String toString() { | |
| 643 String result = "TimeoutException"; | |
| 644 if (duration != null) result = "TimeoutException after $duration"; | |
| 645 if (message != null) result = "$result: $message"; | |
| 646 return result; | |
| 647 } | |
| 648 } | |
| 649 | |
| 650 /** | |
| 651 * A way to produce Future objects and to complete them later | |
| 652 * with a value or error. | |
| 653 * | |
| 654 * Most of the time, the simplest way to create a future is to just use | |
| 655 * one of the [Future] constructors to capture the result of a single | |
| 656 * asynchronous computation: | |
| 657 * | |
| 658 * new Future(() { doSomething(); return result; }); | |
| 659 * | |
| 660 * or, if the future represents the result of a sequence of asynchronous | |
| 661 * computations, they can be chained using [Future.then] or similar functions | |
| 662 * on [Future]: | |
| 663 * | |
| 664 * Future doStuff(){ | |
| 665 * return someAsyncOperation().then((result) { | |
| 666 * return someOtherAsyncOperation(result); | |
| 667 * }); | |
| 668 * } | |
| 669 * | |
| 670 * If you do need to create a Future from scratch — for example, | |
| 671 * when you're converting a callback-based API into a Future-based | |
| 672 * one — you can use a Completer as follows: | |
| 673 * | |
| 674 * class AsyncOperation { | |
| 675 * Completer _completer = new Completer(); | |
| 676 * | |
| 677 * Future<T> doOperation() { | |
| 678 * _startOperation(); | |
| 679 * return _completer.future; // Send future object back to client. | |
| 680 * } | |
| 681 * | |
| 682 * // Something calls this when the value is ready. | |
| 683 * void _finishOperation(T result) { | |
| 684 * _completer.complete(result); | |
| 685 * } | |
| 686 * | |
| 687 * // If something goes wrong, call this. | |
| 688 * void _errorHappened(error) { | |
| 689 * _completer.completeError(error); | |
| 690 * } | |
| 691 * } | |
| 692 */ | |
| 693 abstract class Completer<T> { | |
| 694 | |
| 695 /** | |
| 696 * Creates a new completer. | |
| 697 * | |
| 698 * The general workflow for creating a new future is to 1) create a | |
| 699 * new completer, 2) hand out its future, and, at a later point, 3) invoke | |
| 700 * either [complete] or [completeError]. | |
| 701 * | |
| 702 * The completer completes the future asynchronously. That means that | |
| 703 * callbacks registered on the future, are not called immediately when | |
| 704 * [complete] or [completeError] is called. Instead the callbacks are | |
| 705 * delayed until a later microtask. | |
| 706 * | |
| 707 * Example: | |
| 708 * | |
| 709 * var completer = new Completer(); | |
| 710 * handOut(completer.future); | |
| 711 * later: { | |
| 712 * completer.complete('completion value'); | |
| 713 * } | |
| 714 */ | |
| 715 factory Completer() => new _AsyncCompleter<T>(); | |
| 716 | |
| 717 /** | |
| 718 * Completes the future synchronously. | |
| 719 * | |
| 720 * This constructor should be avoided unless the completion of the future is | |
| 721 * known to be the final result of another asynchronous operation. If in doubt | |
| 722 * use the default [Completer] constructor. | |
| 723 * | |
| 724 * Using an normal, asynchronous, completer will never give the wrong | |
| 725 * behavior, but using a synchronous completer incorrectly can cause | |
| 726 * otherwise correct programs to break. | |
| 727 * | |
| 728 * A synchronous completer is only intended for optimizing event | |
| 729 * propagation when one asynchronous event immediately triggers another. | |
| 730 * It should not be used unless the calls to [complete] and [completeError] | |
| 731 * are guaranteed to occur in places where it won't break `Future` invariants. | |
| 732 * | |
| 733 * Completing synchronously means that the completer's future will be | |
| 734 * completed immediately when calling the [complete] or [completeError] | |
| 735 * method on a synchronous completer, which also calls any callbacks | |
| 736 * registered on that future. | |
| 737 * | |
| 738 * Completing synchronously must not break the rule that when you add a | |
| 739 * callback on a future, that callback must not be called until the code | |
| 740 * that added the callback has completed. | |
| 741 * For that reason, a synchronous completion must only occur at the very end | |
| 742 * (in "tail position") of another synchronous event, | |
| 743 * because at that point, completing the future immediately is be equivalent | |
| 744 * to returning to the event loop and completing the future in the next | |
| 745 * microtask. | |
| 746 * | |
| 747 * Example: | |
| 748 * | |
| 749 * var completer = new Completer.sync(); | |
| 750 * // The completion is the result of the asynchronous onDone event. | |
| 751 * // No other operation is performed after the completion. It is safe | |
| 752 * // to use the Completer.sync constructor. | |
| 753 * stream.listen(print, onDone: () { completer.complete("done"); }); | |
| 754 * | |
| 755 * Bad example. Do not use this code. Only for illustrative purposes: | |
| 756 * | |
| 757 * var completer = new Completer.sync(); | |
| 758 * completer.future.then((_) { bar(); }); | |
| 759 * // The completion is the result of the asynchronous onDone event. | |
| 760 * // However, there is still code executed after the completion. This | |
| 761 * // operation is *not* safe. | |
| 762 * stream.listen(print, onDone: () { | |
| 763 * completer.complete("done"); | |
| 764 * foo(); // In this case, foo() runs after bar(). | |
| 765 * }); | |
| 766 */ | |
| 767 factory Completer.sync() => new _SyncCompleter<T>(); | |
| 768 | |
| 769 /** The future that will contain the result provided to this completer. */ | |
| 770 Future<T> get future; | |
| 771 | |
| 772 /** | |
| 773 * Completes [future] with the supplied values. | |
| 774 * | |
| 775 * The value must be either a value of type [T] | |
| 776 * or a future of type `Future<T>`. | |
| 777 * | |
| 778 * If the value is itself a future, the completer will wait for that future | |
| 779 * to complete, and complete with the same result, whether it is a success | |
| 780 * or an error. | |
| 781 * | |
| 782 * Calling `complete` or [completeError] must not be done more than once. | |
| 783 * | |
| 784 * All listeners on the future are informed about the value. | |
| 785 */ | |
| 786 void complete([value]); | |
| 787 | |
| 788 /** | |
| 789 * Complete [future] with an error. | |
| 790 * | |
| 791 * Calling [complete] or `completeError` must not be done more than once. | |
| 792 * | |
| 793 * Completing a future with an error indicates that an exception was thrown | |
| 794 * while trying to produce a value. | |
| 795 * | |
| 796 * If [error] is `null`, it is replaced by a [NullThrownError]. | |
| 797 * | |
| 798 * If `error` is a `Future`, the future itself is used as the error value. | |
| 799 * If you want to complete with the result of the future, you can use: | |
| 800 * | |
| 801 * thisCompleter.complete(theFuture) | |
| 802 * | |
| 803 * or if you only want to handle an error from the future: | |
| 804 * | |
| 805 * theFuture.catchError(thisCompleter.completeError); | |
| 806 * | |
| 807 */ | |
| 808 void completeError(Object error, [StackTrace stackTrace]); | |
| 809 | |
| 810 /** | |
| 811 * Whether the future has been completed. | |
| 812 */ | |
| 813 bool get isCompleted; | |
| 814 } | |
| 815 | |
| 816 // Helper function completing a _Future with error, but checking the zone | |
| 817 // for error replacement first. | |
| 818 void _completeWithErrorCallback(_Future result, error, stackTrace) { | |
| 819 AsyncError replacement = Zone.current.errorCallback(error, stackTrace); | |
| 820 if (replacement != null) { | |
| 821 error = _nonNullError(replacement.error); | |
| 822 stackTrace = replacement.stackTrace; | |
| 823 } | |
| 824 result._completeError(error, stackTrace); | |
| 825 } | |
| 826 | |
| 827 /** Helper function that converts `null` to a [NullThrownError]. */ | |
| 828 Object _nonNullError(Object error) => | |
| 829 (error != null) ? error : new NullThrownError(); | |
| OLD | NEW |