OLD | NEW |
1 // Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file | 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 | 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. | 3 // BSD-style license that can be found in the LICENSE file. |
4 | 4 |
5 part of dart.async; | 5 part of dart.async; |
6 | 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 |
7 /** | 47 /** |
8 * An object representing a delayed computation. | 48 * An object representing a delayed computation. |
9 * | 49 * |
10 * A [Future] is used to represent a potential value, or error, | 50 * A [Future] is used to represent a potential value, or error, |
11 * that will be available at some time in the future. | 51 * that will be available at some time in the future. |
12 * Receivers of a [Future] can register callbacks | 52 * Receivers of a [Future] can register callbacks |
13 * that handle the value or error once it is available. | 53 * that handle the value or error once it is available. |
14 * For example: | 54 * For example: |
15 * | 55 * |
16 * Future<int> future = getFuture(); | 56 * Future<int> future = getFuture(); |
(...skipping 201 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... |
218 * If calling [computation] throws, the created future will complete with the | 258 * If calling [computation] throws, the created future will complete with the |
219 * error. | 259 * error. |
220 * | 260 * |
221 * See also [Completer] for a way to create and complete a future at a | 261 * See also [Completer] for a way to create and complete a future at a |
222 * later time that isn't necessarily after a known fixed duration. | 262 * later time that isn't necessarily after a known fixed duration. |
223 */ | 263 */ |
224 factory Future.delayed(Duration duration, [computation()]) { | 264 factory Future.delayed(Duration duration, [computation()]) { |
225 _Future<T> result = new _Future<T>(); | 265 _Future<T> result = new _Future<T>(); |
226 new Timer(duration, () { | 266 new Timer(duration, () { |
227 try { | 267 try { |
228 result._complete(computation == null ? null : computation()); | 268 result._complete(computation?.call()); |
229 } catch (e, s) { | 269 } catch (e, s) { |
230 _completeWithErrorCallback(result, e, s); | 270 _completeWithErrorCallback(result, e, s); |
231 } | 271 } |
232 }); | 272 }); |
233 return result; | 273 return result; |
234 } | 274 } |
235 | 275 |
236 /** | 276 /** |
237 * Wait for all the given futures to complete and collect their values. | 277 * Wait for all the given futures to complete and collect their values. |
238 * | 278 * |
239 * Returns a future which will complete once all the futures in a list are | 279 * Returns a future which will complete once all the futures in a list are |
240 * complete. If any of the futures in the list completes with an error, | 280 * complete. If any of the futures in the list completes with an error, |
241 * the resulting future also completes with an error. Otherwise the value | 281 * the resulting future also completes with an error. Otherwise the value |
242 * of the returned future will be a list of all the values that were | 282 * of the returned future will be a list of all the values that were |
243 * produced. | 283 * produced. |
244 * | 284 * |
245 * If `eagerError` is true, the future completes with an error immediately on | 285 * If `eagerError` is true, the future completes with an error immediately on |
246 * the first error from one of the futures. Otherwise all futures must | 286 * the first error from one of the futures. Otherwise all futures must |
247 * complete before the returned future is completed (still with the first | 287 * complete before the returned future is completed (still with the first |
248 * error to occur, the remaining errors are silently dropped). | 288 * error to occur, the remaining errors are silently dropped). |
249 * | 289 * |
250 * If [cleanUp] is provided, in the case of an error, any non-null result of | 290 * If [cleanUp] is provided, in the case of an error, any non-null result of |
251 * a successful future is passed to `cleanUp`, which can then release any | 291 * a successful future is passed to `cleanUp`, which can then release any |
252 * resources that the successful operation allocated. | 292 * resources that the successful operation allocated. |
253 * | 293 * |
254 * The call to `cleanUp` should not throw. If it does, the error will be an | 294 * The call to `cleanUp` should not throw. If it does, the error will be an |
255 * uncaught asynchronous error. | 295 * uncaught asynchronous error. |
256 */ | 296 */ |
257 static Future<List/*<T>*/> wait/*<T>*/(Iterable<Future/*<T>*/> futures, | 297 static Future<List<T>> wait<T>(Iterable<Future<T>> futures, |
258 {bool eagerError: false, | 298 {bool eagerError: false, |
259 void cleanUp(/*=T*/ successValue)}) { | 299 void cleanUp(T successValue)}) { |
260 final _Future<List/*<T>*/> result = new _Future<List/*<T>*/>(); | 300 final _Future<List<T>> result = new _Future<List<T>>(); |
261 List/*<T>*/ values; // Collects the values. Set to null on error. | 301 List<T> values; // Collects the values. Set to null on error. |
262 int remaining = 0; // How many futures are we waiting for. | 302 int remaining = 0; // How many futures are we waiting for. |
263 var error; // The first error from a future. | 303 var error; // The first error from a future. |
264 StackTrace stackTrace; // The stackTrace that came with the error. | 304 StackTrace stackTrace; // The stackTrace that came with the error. |
265 | 305 |
266 // Handle an error from any of the futures. | 306 // Handle an error from any of the futures. |
267 void handleError(theError, theStackTrace) { | 307 void handleError(theError, theStackTrace) { |
268 remaining--; | 308 remaining--; |
269 if (values != null) { | 309 if (values != null) { |
270 if (cleanUp != null) { | 310 if (cleanUp != null) { |
271 for (var value in values) { | 311 for (var value in values) { |
272 if (value != null) { | 312 if (value != null) { |
273 // Ensure errors from cleanUp are uncaught. | 313 // Ensure errors from cleanUp are uncaught. |
274 new Future.sync(() { cleanUp(value); }); | 314 new Future.sync(() { cleanUp(value); }); |
275 } | 315 } |
276 } | 316 } |
277 } | 317 } |
278 values = null; | 318 values = null; |
279 if (remaining == 0 || eagerError) { | 319 if (remaining == 0 || eagerError) { |
280 result._completeError(theError, theStackTrace); | 320 result._completeError(theError, theStackTrace); |
281 } else { | 321 } else { |
282 error = theError; | 322 error = theError; |
283 stackTrace = theStackTrace; | 323 stackTrace = theStackTrace; |
284 } | 324 } |
285 } else if (remaining == 0 && !eagerError) { | 325 } else if (remaining == 0 && !eagerError) { |
286 result._completeError(error, stackTrace); | 326 result._completeError(error, stackTrace); |
287 } | 327 } |
288 } | 328 } |
289 | 329 |
290 // As each future completes, put its value into the corresponding | 330 try { |
291 // position in the list of values. | 331 // As each future completes, put its value into the corresponding |
292 for (Future future in futures) { | 332 // position in the list of values. |
293 int pos = remaining++; | 333 for (Future future in futures) { |
294 future.then((Object/*=T*/ value) { | 334 int pos = remaining; |
295 remaining--; | 335 future.then((T value) { |
296 if (values != null) { | 336 remaining--; |
297 values[pos] = value; | 337 if (values != null) { |
298 if (remaining == 0) { | 338 values[pos] = value; |
299 result._completeWithValue(values); | 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 } |
300 } | 350 } |
301 } else { | 351 }, onError: handleError); |
302 if (cleanUp != null && value != null) { | 352 // Increment the 'remaining' after the call to 'then'. |
303 // Ensure errors from cleanUp are uncaught. | 353 // If that call throws, we don't expect any future callback from |
304 new Future.sync(() { cleanUp(value); }); | 354 // the future, and we also don't increment remaining. |
305 } | 355 remaining++; |
306 if (remaining == 0 && !eagerError) { | 356 } |
307 result._completeError(error, stackTrace); | 357 if (remaining == 0) { |
308 } | 358 return new Future.value(const []); |
309 } | 359 } |
310 }, onError: handleError); | 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 } |
311 } | 379 } |
312 if (remaining == 0) { | |
313 return new Future.value(const []); | |
314 } | |
315 values = new List/*<T>*/(remaining); | |
316 return result; | 380 return result; |
317 } | 381 } |
318 | 382 |
319 /** | 383 /** |
320 * Returns the result of the first future in [futures] to complete. | 384 * Returns the result of the first future in [futures] to complete. |
321 * | 385 * |
322 * The returned future is completed with the result of the first | 386 * The returned future is completed with the result of the first |
323 * future in [futures] to report that it is complete. | 387 * future in [futures] to report that it is complete. |
324 * The results of all the other futures are discarded. | 388 * The results of all the other futures are discarded. |
325 * | 389 * |
326 * If [futures] is empty, or if none of its futures complete, | 390 * If [futures] is empty, or if none of its futures complete, |
327 * the returned future never completes. | 391 * the returned future never completes. |
328 */ | 392 */ |
329 static Future/*<T>*/ any/*<T>*/(Iterable<Future/*<T>*/> futures) { | 393 static Future<T> any<T>(Iterable<Future<T>> futures) { |
330 var completer = new Completer/*<T>*/.sync(); | 394 var completer = new Completer<T>.sync(); |
331 var onValue = (/*=T*/ value) { | 395 var onValue = (T value) { |
332 if (!completer.isCompleted) completer.complete(value); | 396 if (!completer.isCompleted) completer.complete(value); |
333 }; | 397 }; |
334 var onError = (error, stack) { | 398 var onError = (error, stack) { |
335 if (!completer.isCompleted) completer.completeError(error, stack); | 399 if (!completer.isCompleted) completer.completeError(error, stack); |
336 }; | 400 }; |
337 for (var future in futures) { | 401 for (var future in futures) { |
338 future.then(onValue, onError: onError); | 402 future.then(onValue, onError: onError); |
339 } | 403 } |
340 return completer.future; | 404 return completer.future; |
341 } | 405 } |
(...skipping 14 matching lines...) Expand all Loading... |
356 */ | 420 */ |
357 static Future forEach(Iterable input, f(element)) { | 421 static Future forEach(Iterable input, f(element)) { |
358 Iterator iterator = input.iterator; | 422 Iterator iterator = input.iterator; |
359 return doWhile(() { | 423 return doWhile(() { |
360 if (!iterator.moveNext()) return false; | 424 if (!iterator.moveNext()) return false; |
361 return new Future.sync(() => f(iterator.current)).then((_) => true); | 425 return new Future.sync(() => f(iterator.current)).then((_) => true); |
362 }); | 426 }); |
363 } | 427 } |
364 | 428 |
365 /** | 429 /** |
366 * Perform an async operation repeatedly until it returns `false`. | 430 * Performs an async operation repeatedly until it returns `false`. |
367 * | 431 * |
368 * Runs [f] repeatedly, starting the next iteration only when the [Future] | 432 * The function [f] is called repeatedly while it returns either the [bool] |
369 * returned by [f] completes to `true`. Returns a [Future] that completes once | 433 * value `true` or a [Future] which completes with the value `true`. |
370 * [f] returns `false`. | |
371 * | 434 * |
372 * The return values of all [Future]s are discarded. Any errors will cause the | 435 * If a call to [f] returns `false` or a [Future] that completes to `false`, |
373 * iteration to stop and will be piped through the returned [Future]. | 436 * iteration ends and the future returned by [doWhile] is completed. |
374 * | 437 * |
375 * The function [f] may return either a [bool] or a [Future] that completes to | 438 * If a future returned by [f] completes with an error, iteration ends and |
376 * a [bool]. If it returns a non-[Future], iteration continues immediately. | 439 * the future returned by [doWhile] completes with the same error. |
377 * Otherwise it waits for the returned [Future] to complete. | 440 * |
| 441 * The [f] function must return either a `bool` value or a [Future] completing |
| 442 * with a `bool` value. |
378 */ | 443 */ |
379 static Future doWhile(f()) { | 444 static Future doWhile(f()) { |
380 _Future doneSignal = new _Future(); | 445 _Future doneSignal = new _Future(); |
381 var nextIteration; | 446 var nextIteration; |
382 // Bind this callback explicitly so that each iteration isn't bound in the | 447 // Bind this callback explicitly so that each iteration isn't bound in the |
383 // context of all the previous iterations' callbacks. | 448 // context of all the previous iterations' callbacks. |
384 nextIteration = Zone.current.bindUnaryCallback((bool keepGoing) { | 449 nextIteration = Zone.current.bindUnaryCallback((bool keepGoing) { |
385 if (keepGoing) { | 450 if (keepGoing) { |
386 new Future.sync(f).then(nextIteration, | 451 new Future.sync(f).then(nextIteration, |
387 onError: doneSignal._completeError); | 452 onError: doneSignal._completeError); |
(...skipping 37 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... |
425 * the future returned by `then` will be completed with | 490 * the future returned by `then` will be completed with |
426 * the same result as the future returned by the callback. | 491 * the same result as the future returned by the callback. |
427 * | 492 * |
428 * If [onError] is not given, and this future completes with an error, | 493 * If [onError] is not given, and this future completes with an error, |
429 * the error is forwarded directly to the returned future. | 494 * the error is forwarded directly to the returned future. |
430 * | 495 * |
431 * In most cases, it is more readable to use [catchError] separately, possibly | 496 * In most cases, it is more readable to use [catchError] separately, possibly |
432 * with a `test` parameter, instead of handling both value and error in a | 497 * with a `test` parameter, instead of handling both value and error in a |
433 * single [then] call. | 498 * single [then] call. |
434 */ | 499 */ |
435 Future/*<S>*/ then/*<S>*/(onValue(T value), { Function onError }); | 500 Future<S> then<S>(FutureOr<S> onValue(T value), { Function onError }); |
436 | 501 |
437 /** | 502 /** |
438 * Handles errors emitted by this [Future]. | 503 * Handles errors emitted by this [Future]. |
439 * | 504 * |
440 * This is the asynchronous equivalent of a "catch" block. | 505 * This is the asynchronous equivalent of a "catch" block. |
441 * | 506 * |
442 * Returns a new [Future] that will be completed with either the result of | 507 * Returns a new [Future] that will be completed with either the result of |
443 * this future or the result of calling the `onError` callback. | 508 * this future or the result of calling the `onError` callback. |
444 * | 509 * |
445 * If this future completes with a value, | 510 * If this future completes with a value, |
(...skipping 42 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... |
488 */ | 553 */ |
489 // The `Function` below can stand for several types: | 554 // The `Function` below can stand for several types: |
490 // - (dynamic) -> T | 555 // - (dynamic) -> T |
491 // - (dynamic, StackTrace) -> T | 556 // - (dynamic, StackTrace) -> T |
492 // - (dynamic) -> Future<T> | 557 // - (dynamic) -> Future<T> |
493 // - (dynamic, StackTrace) -> Future<T> | 558 // - (dynamic, StackTrace) -> Future<T> |
494 // Given that there is a `test` function that is usually used to do an | 559 // Given that there is a `test` function that is usually used to do an |
495 // `isCheck` we should also expect functions that take a specific argument. | 560 // `isCheck` we should also expect functions that take a specific argument. |
496 // Note: making `catchError` return a `Future<T>` in non-strong mode could be | 561 // Note: making `catchError` return a `Future<T>` in non-strong mode could be |
497 // a breaking change. | 562 // a breaking change. |
498 Future/*<T>*/ catchError(Function onError, | 563 Future<T> catchError(Function onError, |
499 {bool test(Object error)}); | 564 {bool test(Object error)}); |
500 | 565 |
501 /** | 566 /** |
502 * Register a function to be called when this future completes. | 567 * Register a function to be called when this future completes. |
503 * | 568 * |
504 * The [action] function is called when this future completes, whether it | 569 * The [action] function is called when this future completes, whether it |
505 * does so with a value or with an error. | 570 * does so with a value or with an error. |
506 * | 571 * |
507 * This is the asynchronous equivalent of a "finally" block. | 572 * This is the asynchronous equivalent of a "finally" block. |
508 * | 573 * |
(...skipping 246 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... |
755 if (replacement != null) { | 820 if (replacement != null) { |
756 error = _nonNullError(replacement.error); | 821 error = _nonNullError(replacement.error); |
757 stackTrace = replacement.stackTrace; | 822 stackTrace = replacement.stackTrace; |
758 } | 823 } |
759 result._completeError(error, stackTrace); | 824 result._completeError(error, stackTrace); |
760 } | 825 } |
761 | 826 |
762 /** Helper function that converts `null` to a [NullThrownError]. */ | 827 /** Helper function that converts `null` to a [NullThrownError]. */ |
763 Object _nonNullError(Object error) => | 828 Object _nonNullError(Object error) => |
764 (error != null) ? error : new NullThrownError(); | 829 (error != null) ? error : new NullThrownError(); |
OLD | NEW |