You*_*mal 5 asynchronous async-await dart flutter
基于 Dart 官方页面 当使用Async/Wait时:
\n\n当应用程序看到这个单词时,async
它通常会同步执行该函数,直到它看到await
或return
\n\n\n请注意,异步函数立即开始执行\n(同步)。当函数第一次出现以下任一情况时,\n 会暂停执行并返回未完成的 future:\n:
\n\n\n
\n- 函数\xe2\x80\x99s 第一个await 表达式(在函数从该表达式获取\n 未完成的future 之后)。
\n- 函数中的任何 return 语句。
\n- 函数体结束。
\n
当它看到其中任何一个函数时,它会返回一个未完成的值 Future
并停止执行该async
函数,直到执行完所有其他函数为止,当执行完所有其他函数后,应用程序将返回到该函数async
并执行其中的内容它。
这是 Dart 官方页面上的一张照片,更详细地解释了它:
\n
但是,当我测试时,我尝试print
在返回未来结果之前添加一条语句,如下面的代码所示,但结果并不像网站中所述,因为它说应用程序停止执行一旦它看到这个词,await
但声明:“Async - Hi Called 1st”被打印,正如您在执行其他函数之前看到的那样。
import \'dart:async\';\n\nFuture<void> print1stAsync() async {\n var test = await callAsync();\n print(test);\n}\n\nmain() {\n print1stAsync();\n print2nd();\n print3rd();\n print4th();\n}\n\nprint2nd() {\n print(\'Called 2nd\');\n}\n\nprint3rd() {\n print("Called 3rd");\n}\n\nprint4th() {\n print(\'Called 4th\');\n}\n\nFuture<String> callAsync() {\n print("Async - Hi Called 1st");\n return Future(() => "Async - Called 1st ");\n }\n
Run Code Online (Sandbox Code Playgroud)\n\n输出:
\n\nAsync - Hi Called 1st\nCalled 2nd\nCalled 3rd\nCalled 4th\nAsync - Called 1st \n
Run Code Online (Sandbox Code Playgroud)\n\n那么为什么会发生这种情况呢?我想念明白了什么吗?
\n应用程序不会停止执行,只是延迟执行之后的代码,await
直到返回Future
完成。
您还需要等待对异步函数的调用,否则在调用后继续print1stAsync()
执行(在调用之后,而不是在它返回完成之后)main
callAsync();
Future
main() async {
await print1stAsync();
print2nd();
print3rd();
print4th();
}
Run Code Online (Sandbox Code Playgroud)
添加async
到函数也意味着该函数返回一个Future
. 无法从异步返回到同步。异步具有传染性。
await callAsync();
意味着同一函数内该行下方的代码(如print(test);
您的示例中)将被延迟。
它没有说明 callAsync() 中的代码或调用的代码print1stAsync();
归档时间: |
|
查看次数: |
20876 次 |
最近记录: |