Skip to content

Instantly share code, notes, and snippets.

@noboru-i
Last active August 30, 2023 03:49
Show Gist options
  • Select an option

  • Save noboru-i/6bc0451f6b97182649eb07c5ab31f51c to your computer and use it in GitHub Desktop.

Select an option

Save noboru-i/6bc0451f6b97182649eb07c5ab31f51c to your computer and use it in GitHub Desktop.
Call async function from non-async function

Call async function from non-async function

Created with <3 with dartpad.dev.

DartPadでの実行結果は以下のようになった。 https://dartpad.dev/?id=6bc0451f6b97182649eb07c5ab31f51c

main: before someFutureFunc
someFutureFunc: before wait
main: after someFutureFunc
(3秒程度経った後、次が表示される)
someFutureFunc: after wait
  • non-async functionでは、 await することが出来ない。
  • async function 内で、 await をするまでは、同期的に実行される。(おそらく)
  • await した時点で制御が戻り、 main function側の続きが実行される(おそらく)
  • async function 内は、そのまま処理が継続される(処理系に依存する?)
void main() {
print('main: before someFutureFunc');
someFutureFunc();
print('main: after someFutureFunc');
}
Future<void> someFutureFunc() async {
print('someFutureFunc: before wait');
await Future.delayed(const Duration(seconds: 3));
print('someFutureFunc: after wait');
}
@noboru-i
Copy link
Author

https://dart.dev/codelabs/async-await#execution-flow-with-async-and-await

Execution flow with async and await
An async function runs synchronously until the first await keyword. This means that within an async function body, all synchronous code before the first await keyword executes immediately.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment