OLD | NEW |
(Empty) | |
| 1 when [](https://pub.dartlang
.org/packages/when) [](https://drone.io/github.com/seaneagan/when.dart/latest) [](https:/
/coveralls.io/r/seaneagan/when.dart?branch=master) |
| 2 ==== |
| 3 |
| 4 It's often useful to provide sync (convenient) and async (concurrent) versions |
| 5 of the same API. `dart:io` does this with many APIs including [Process.run][] |
| 6 and [Process.runSync][]. Since the sync and async versions do the same thing, |
| 7 much of the logic is the same, with just a few small bits differing in their |
| 8 sync vs. async implementation. |
| 9 |
| 10 The `when` function allows for registering `onSuccess`, `onError`, and |
| 11 `onComplete` callbacks on another callback which represents that sync/async |
| 12 dependent part of the API. If the callback is sync (returns a non-`Future` or |
| 13 throws), then the other callbacks are invoked synchronously, otherwise the |
| 14 other callbacks are registered on the returned `Future`. |
| 15 |
| 16 For example, here's how it can be used to implement sync and async APIs for |
| 17 reading a JSON data structure from the file system with file absence handling: |
| 18 |
| 19 ```dart |
| 20 import 'dart:async'; |
| 21 import 'dart:convert'; |
| 22 import 'dart:io'; |
| 23 |
| 24 import 'package:when/when.dart'; |
| 25 |
| 26 /// Reads and decodes JSON from [path] asynchronously. |
| 27 /// |
| 28 /// If [path] does not exist, returns the result of calling [onAbsent]. |
| 29 Future readJsonFile(String path, {onAbsent()}) => _readJsonFile( |
| 30 path, onAbsent, (file) => file.exists(), (file) => file.readAsString()); |
| 31 |
| 32 /// Reads and decodes JSON from [path] synchronously. |
| 33 /// |
| 34 /// If [path] does not exist, returns the result of calling [onAbsent]. |
| 35 readJsonFileSync(String path, {onAbsent()}) => _readJsonFile( |
| 36 path, onAbsent, (file) => file.existsSync(), |
| 37 (file) => file.readAsStringSync()); |
| 38 |
| 39 _readJsonFile(String path, onAbsent(), exists(File file), read(File file)) { |
| 40 var file = new File(path); |
| 41 return when( |
| 42 () => exists(file), |
| 43 onSuccess: (doesExist) => doesExist ? |
| 44 when(() => read(file), onSuccess: JSON.decode) : |
| 45 onAbsent()); |
| 46 } |
| 47 |
| 48 main() { |
| 49 var syncJson = readJsonFileSync('foo.json', onAbsent: () => {'foo': 'bar'}); |
| 50 print('Sync json: $syncJson'); |
| 51 readJsonFile('foo.json', onAbsent: () => {'foo': 'bar'}).then((asyncJson) { |
| 52 print('Async json: $asyncJson'); |
| 53 }); |
| 54 } |
| 55 ``` |
| 56 |
| 57 [Process.run]: https://api.dartlang.org/apidocs/channels/stable/dartdoc-viewer/d
art:io.Process#id_run |
| 58 [Process.runSync]: https://api.dartlang.org/apidocs/channels/stable/dartdoc-view
er/dart:io.Process#id_runSync |
OLD | NEW |