I'm playing with a tiny web server and I'm implementing one version using the async
package, and one synchronous version executing each request in a separate isolate. I would like to simply pipe a file stream to the HttpResponse
, but I can't do that synchronously. And I can't find a way to wait for neither the Stream
nor a Future
synchronously. I'm now using a RandomAccessFile
instead which works, but it becomes messier.
One solution would be to execute a periodical timer to check if the future is completed (by setting a boolean or similar), but that is most definitely not something I want to use.
Is there a way to wait synchronously for a Future
and a Stream
? If not, why?
await: You can use the await keyword to get the completed result of an asynchronous expression. The await keyword only works within an async function.
According to the flutter docs, Future. wait() : Returns a future which will complete once all the provided futures have completed, either with their results, or with an error if any of the provided futures fail. In the JavaScript world, this is achievable with Promise.
Dart Future Several of Dart's built-in classes return a Future when an asynchronous method is called. Dart is a single-threaded programming language. If any code blocks the thread of execution (for example, by waiting for a time-consuming operation or blocking on I/O), the program effectively freezes.
A Future represents a computation that doesn't complete immediately. Where a normal function returns the result, an asynchronous function returns a Future, which will eventually contain the result. The future will tell you when the result is ready. A stream is a sequence of asynchronous events.
For future visitors coming here simply wanting to perform some task after a Future or Stream completes, use await
and await for
inside an async method.
final myInt = await getFutureInt();
int mySum = 0;
await for (int someInt in myIntStream) {
mySum += someInt;
}
This may be technically different than performing a synchronous task, but it achieves the goal of completing one task before doing another one.
AFAIK there isn't a way to wait synchronously for a Future or a Stream. Why? Because these are asynchronous pretty much definitionally, and as you are discovering, the APIs are designed with asynchronous behavior in mind.
There are a couple of Future constructors, Future.value()
and Future.sync()
, that execute immediately, but I don't think these are probably what you have in mind.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With