Created with <3 with dartpad.dev.
Last active
September 11, 2023 11:02
-
-
Save bfritscher/908a9d372a0ab38713775c431ad397d1 to your computer and use it in GitHub Desktop.
dart-future-async-await
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
void main() { | |
performTasks(); | |
performTasksAsync(); | |
} | |
void performTasks() { | |
String result = ''; | |
Future<String> f; | |
result = task1(); | |
print (result); | |
result = task2(); | |
print (result); | |
f = task3(); | |
print (f); | |
f.then((result) { | |
print('Task 3 then: $result'); | |
task4().then((result) { | |
print('Task 4 then: $result'); | |
}); | |
}); | |
f = task4(); | |
print(f); | |
task5().catchError((e) { | |
print('erro: $e'); | |
return ''; | |
}); | |
} | |
void performTasksAsync() async { | |
String result = ''; | |
result = task1(); | |
print (result); | |
result = task2(); | |
print (result); | |
result = await task3(); | |
print (result); | |
result = await task4(); | |
print(result); | |
try { | |
await task5(); | |
} catch(e) { | |
print('erro: $e'); | |
} | |
print('start task 3&4'); | |
await Future.wait([task3(), task4()]); | |
print('task 3&4 completed'); | |
} | |
String task1() { | |
print('Task 1 complete'); | |
return "data1"; | |
} | |
String task2() { | |
print('Task 2 complete'); | |
return 'data2'; | |
} | |
Future<String> task3() async { | |
print('Task 3 start'); | |
// Using a delay to simulate a future as would be returned by a http call | |
return Future.delayed(const Duration(seconds:2), () { | |
print('Task 3 complete'); | |
return 'data3'; | |
}); | |
} | |
Future<String> task4() async { | |
print('Task 4 start'); | |
// Using a delay to simulate a future as would be returned by a http call | |
return Future.delayed(const Duration(seconds:1), () { | |
print('Task 4 complete'); | |
return 'data4'; | |
}); | |
} | |
Future<String> task5() async { | |
print('Task 5 start'); | |
// Using a delay to simulate a future as would be returned by a http call | |
throw Exception('Task 5 Error'); | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment