android - 如果我的函数调用异步函数,是否会迫使我让我的函数返回 Future?

标签 android ios flutter dart asynchronous

我正在了解 asyncawait在达特中。在大多数情况下,这是一种表示某些函数需要一段时间并且程序应该异步运行特定函数的方式。

我不明白的是这如何影响最终导致给定异步函数的所有“前面”函数。

例如,

import 'dart:async';

Future<String> firstAsync() async {
  await Future<String>.delayed(const Duration(seconds: 2));
  return "First!";
}

String secondAsync() async {
  var returnVal = await firstAsync();
  return returnVal;
}

void main() {
  var s = secondAsync();

  if (s == "First!") {
    ///run some code...
  }

  print('done');
}
  1. firstAsync返回一个 future,因此该函数的返回值为 Future<String> 是有道理的。 。然后,secondAsync使用此功能。这是否意味着secondAsync还必须返回Future<String>

  2. main需要async关键字,我需要将其第一行更改为 var s = await secondAsync();

  3. 如果是这样,是否意味着 main还需要标记为返回 Future<void>

最佳答案

If my function calls an asynchronous function, does that force me to make my function return a Future?

不一定,但几乎总是如此。如果您的函数需要返回一个依赖于被调用的异步函数的结果,那么您的函数也是隐式异步的,并且必须返回 Future .

如果函数的调用者不需要在函数完成时收到通知,那么您的函数是 "fire-and-forget" and can return void instead of a Future 。或者,如果您的函数不依赖于被调用的异步函数(即,您正在调用“即发即忘”异步函数),那么您的函数可以返回它想要的任何内容。它不会等待任何事情。

  1. firstAsync returns a future, so it makes sense that the function's return value is Future<String>. Then, secondAsync uses this function. Does that mean that secondAsync must also return Future<String>?

是的。

  1. Does main need the async keyword and would I need to change its first line to var s = await secondAsync(); ?

技术上不行(您可以直接使用原始 Future API 而不是使用 await ),但您应该更喜欢使用 async/await 。更容易理解。

  1. And if so, does that mean that main also needs to be marked as returning Future<void>?

main通常没有调用者需要等待它完成(Dart VM/运行时将等到事件队列为空后再退出),所以 main通常可以认为是一劳永逸并且可以返回 void 。目前推荐来自 avoid_void_async lint documentation就是不去打扰main返回 Future .

main返回 Future如果您有递归 main可能很重要函数或者如果你的 .dart文件可能是import由另一个直接调用您的 main() 的文件编辑功能。然而,这些情况非常罕见(并且最好通过重构来避免)。

关于android - 如果我的函数调用异步函数,是否会迫使我让我的函数返回 Future?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72386335/

相关文章:

android - fragment后台任务访问资源经常返回illegalStateException

ios - 尝试在 iOS 中验证电子邮件,崩溃不知道为什么?

http - IOClient 在 Dart http 包中去了哪里?

android - 您上传了以 Debug模式登录的 APK 或 Android App Bundle

flutter - 使用带有 flutter_bloc 的 Equatable 类

android - 如何从 url 在 android 上加载 pdf?

java - 使用许多 editText 和 onclicklistener 时内存不足

android - onStatusChanged 情况

ios - Facebook 登录 Swift

ios - iOS 中 256 block 大小的 AES 256 位加密