Skip to content

Instantly share code, notes, and snippets.

@dnys1
Created August 30, 2023 00:46
Show Gist options
  • Save dnys1/dc5c257693d0d454c819ffcf38b626f0 to your computer and use it in GitHub Desktop.
Save dnys1/dc5c257693d0d454c819ffcf38b626f0 to your computer and use it in GitHub Desktop.
astonishing-spray-3881

astonishing-spray-3881

Created with <3 with dartpad.dev.

import 'dart:async';
void main() async {
// A function marked async will implicitly return a Future.
future(sync: true).then(print);
future(sync: false).then(print);
print('main (sync)');
// clear pending futures
await Future<void>.delayed(Duration.zero);
// We would expect line 13 to print first if it was synchronous.
scheduleMicrotask(() => print('microtask'));
print(await futureOr(sync: true));
print(await futureOr(sync: false));
// clear pending futures
await Future<void>.delayed(Duration.zero);
// Treat FutureOr as a sealed class to avoid unnecessary waits
scheduleMicrotask(() => print('microtask'));
switch (futureOr(sync: true)) {
case final String res: print(res);
case final fut: print(await fut);
}
}
Future<String> future({required bool sync}) async {
if (sync) {
return 'future (sync)';
}
await Future<void>.delayed(Duration.zero);
return 'future (async)';
}
FutureOr<String> futureOr({required bool sync}) {
if (sync) {
return 'future (sync)';
}
return Future.value('future (async)');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment