Chromium Code Reviews| OLD | NEW |
|---|---|
| (Empty) | |
| 1 // Copyright (c) 2013, 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 library utils; | |
| 6 | |
| 7 import 'dart:async'; | |
| 8 | |
| 9 /// Configures [future] so that its result (success or exception) is passed on | |
| 10 /// to [completer]. | |
| 11 void chainToCompleter(Future future, Completer completer) { | |
| 12 future.then((value) => completer.complete(value), | |
| 13 onError: (e) => completer.completeError(e.error, e.stackTrace)); | |
| 14 } | |
| 15 | |
| 16 /// Prepends each line in [text] with [prefix]. | |
| 17 String prefixLines(String text, {String prefix: '| '}) => | |
| 18 text.split('\n').map((line) => '$prefix$line').join('\n'); | |
| 19 | |
| 20 /// Returns a [Future] that completes in [milliseconds]. | |
| 21 Future sleep(int milliseconds) { | |
| 22 var completer = new Completer(); | |
| 23 new Timer(milliseconds, (_) => completer.complete()); | |
| 24 return completer.future; | |
| 25 } | |
|
Bob Nystrom
2013/02/08 16:15:37
Is this being used anywhere?
nweiz
2013/02/08 22:14:38
It's used a bunch in the tests.
| |
| 26 | |
| 27 /// Wraps [input] to provide a timeout. If [input] completes before | |
| 28 /// [milliseconds] have passed, then the return value completes in the same way. | |
| 29 /// However, if [milliseconds] pass before [input] has completed, [onTimeout] is | |
| 30 /// run and its result is passed to [input] (with chaining, if it returns a | |
| 31 /// [Future]). | |
| 32 /// | |
| 33 /// Note that timing out will not cancel the asynchronous operation behind | |
| 34 /// [input]. | |
| 35 Future timeout(Future input, int milliseconds, onTimeout()) { | |
| 36 bool completed = false; | |
| 37 var completer = new Completer(); | |
| 38 var timer = new Timer(milliseconds, (_) { | |
| 39 completed = true; | |
| 40 chainToCompleter(new Future.immediate(null).then((_) => onTimeout()), | |
| 41 completer); | |
| 42 }); | |
| 43 input.then((value) { | |
| 44 if (completed) return; | |
| 45 timer.cancel(); | |
| 46 completer.complete(value); | |
| 47 }).catchError((e) { | |
| 48 if (completed) return; | |
| 49 timer.cancel(); | |
| 50 completer.completeError(e.error, e.stackTrace); | |
| 51 }); | |
| 52 return completer.future; | |
| 53 } | |
| OLD | NEW |