gpt4 book ai didi

asynchronous - async/await - 在 future() 之前不等待 - Dart

转载 作者:IT王子 更新时间:2023-10-29 06:40:29 25 4
gpt4 key购买 nike

基于Dart官方页面使用时Async/Wait :

当应用程序看到单词 async 时,它会正常同步执行函数,直到看到 awaitreturn

Note that an async function starts executing right away (synchronously). The function suspends execution and returns an uncompleted future when it reaches the first occurrence of any of the following:

  • The function’s first await expression (after the function gets the uncompleted future from that expression).
  • Any return statement in the function.
  • The end of the function body.

并且当它看到它们中的任何一个时,它返回一个未完成的Future并停止执行async函数,直到它执行所有其他函数,并且当所有其他函数函数执行后,应用程序返回到 async 函数并执行其中的内容。

这是来自 Dart 官方页面的照片,更详细地解释了它:
Dart Image

但是当我测试时,我试图在返回 future 结果之前添加一个 print 语句,正如您在下面的代码中看到的那样,但结果与网站,因为它说应用程序一旦看到单词 await 就会停止执行,但是语句:“Async - Hi Called 1st” 会像您看到的那样先打印出来功能已执行。

import 'dart:async';

Future<void> print1stAsync() async {
var test = await callAsync();
print(test);
}

main() {
print1stAsync();
print2nd();
print3rd();
print4th();
}

print2nd() {
print('Called 2nd');
}

print3rd() {
print("Called 3rd");
}

print4th() {
print('Called 4th');
}

Future<String> callAsync() {
print("Async - Hi Called 1st");
return Future(() => "Async - Called 1st ");
}

输出:

Async - Hi Called 1st
Called 2nd
Called 3rd
Called 4th
Async - Called 1st

那么为什么会这样呢?我错过了什么吗?

最佳答案

应用程序不会停止执行,只有 await 之后的代码会延迟执行,直到返回的 Future 完成。

您还需要等待对异步函数 print1stAsync() 的调用,否则 main 的执行会在调用 callAsync();(在调用之后,而不是在它返回完成的 Future 之后)

main() async {
await print1stAsync();
print2nd();
print3rd();
print4th();
}

向函数添加async 也意味着该函数返回一个Future。没有办法从异步返回到同步。异步具有传染性。

await callAsync(); 表示同一函数中该行下方的代码(如示例中的 print(test);)将被延迟。
它没有说明 callAsync() 中的代码或调用 print1stAsync();

的代码

关于asynchronous - async/await - 在 future() 之前不等待 - Dart,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53249859/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com