Skip to content

Instantly share code, notes, and snippets.

@aabeben
Created December 17, 2019 01:01
Show Gist options
  • Save aabeben/d1c7b110c2b15296954956c79c2a392d to your computer and use it in GitHub Desktop.
Save aabeben/d1c7b110c2b15296954956c79c2a392d to your computer and use it in GitHub Desktop.
Async
// Hindari neraka panggilnanti dan buat kode anda jadi lebih mudah dibaca
// dengan menggunakan async dan await
const oneSecond = Duration(seconds:1);
// ...
Future<void> printWithDelay(String message) async{
await Future.delayed(oneSecond);
print(message);
}
// metode di atas sama dengan berikut
Future<void> printWithDelay(String message){
return Future.delayed(oneSecond).then((_){
print(message);
});
}
// Pada contoh berikut yang menampilkan, async dan await
// membantu dalam hal membuat kode asynchronous lebih mudah dibaca.
Future<void> createDescriptions(Iterable<String> objects) async {
for(var object in objects){
try{
var file = File('$object');
if(await file.exists()){
var modified = await file.lastModified();
print('File for $object already exists. It was modified on $modified.');
continue;
}
await file.create();
await file.writeAsString('Start describing $object in this file.');
} on IOException catch(e){
print('Cannot create description for $object: $e');
}
}
}
// Anda dapat juga menggunakan async*, yang memberikan anda sebuah cara yang
// menyenangkan dan mudah dibaca dalam hal membangun aliran-aliran.
Stream<String> report(Spacecraft craft, Iterable<String> objects) async* {
for(var object in objects){
await Future.delayed(oneSecond);
yield '${craft.name} flies by $object';
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment