返回void与返回Future

返回void与返回Future

本文介绍了返回void与返回Future< void>有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

返回 void async 方法和返回 Future< void> 的方法之间有区别吗?似乎两者在Dart中都是有效的:

Is there a difference between an async method that returns void, and one that returns Future<void>? It seems that both are valid in Dart:

void main() async {
    await myVoid();
    await myFutureVoid();
}


void myVoid() async {
    // Do something
}


Future<void> myFutureVoid() async {
    // Do something
}

它们相同吗?

如果是这样,为什么在不允许例如 int 的情况下允许 void ?编译器说标记为'async'的函数必须具有可分配给'Future'的返回类型" .

If so, why is void allowed when for example int is not? The compiler says "Functions marked 'async' must have a return type assignable to 'Future'".

推荐答案

void f() Future< void>f()不相同.( async 关键字的存在实际上并不重要. async 关键字主要用于在函数体中使用 await 关键字.)

void f() and Future<void> f() are not identical. (The presence of the async keyword doesn't actually matter. The async keyword primarily enables the use of the await keyword in the function body.)

void f()声明一个不返回任何内容的函数.如果它完成异步工作,则该工作将即兴即忘": f 的调用者没有机会等待它完成.

void f() declares a function that returns nothing. If it does asynchronous work, then that work will be "fire-and-forget": there is no opportunity for the caller of f to wait for it to finish.

相反, Future< void>f()声明一个函数,该函数返回调用者可以等待的 Future (通过使用 await 或注册 Future.then()回调).异步工作没有返回任何值,但是调用者可以确定何时完成.

In contrast, Future<void> f() declares a function that returns a Future that the caller can wait for (either by using await or by registering a Future.then() callback). There's no value returned by the asynchronous work, but callers can determine when it is finished.

通常标有 async 的功能应返回 Future .如果您有一个执行异步工作并产生实际值的函数(例如 int ),则调用方必须等待该值被计算后才能被计算.用过的.因此,该函数必须返回 Future .

Functions marked with async usually should return a Future. If you have a function that does asynchronous work that produces an actual value (such as an int), then the caller must wait for that value to be computed before it can be used. That function therefore must return a Future.

在特殊情况下, async 函数可以返回 void 而不是 Future< void> 来表明它是即发即发的忘了.

As a special case, an async function can return void instead of Future<void> to indicate that it is fire-and-forget.

这篇关于返回void与返回Future&lt; void&gt;有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-04 08:32