Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
741 views
in Technique[技术] by (71.8m points)

asynchronous - What's the difference between returning void vs returning Future<void>?

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
}

Are they identical?

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'".

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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() 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.

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.

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.

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...