Forcing await to return a value in dart

Viewed 25

I know this is such a 101 question but it totally goes against my intuition so I need to ask about it.

Say I make a method:

String read(String key) => return storage.read(key);

Now that's not going to work because storage.read is an asynchronous function. No problem:

String read(String key) => return await storage.read(key);

Now here, I would think that means, wait for this Future to complete then return the resulting String. But that's not ok, because as soon as I use await I need to make my function async too.

String read(String key) async => return await storage.read(key);

Ok, But that doens't work because an async function, apparently by definition, returns a Future (or void).

Future<String> read(String key) async => return await storage.read(key);

And there we go. This function is valid.

So, if I'm using a async function somewhere in my call stack, everything above it has to be an async function, and return a Future, yes?

The reason this goes against my intuition is because I think, why not allow me the control to say, "when you get to this function, (in the call stack) resolve the future into it's actual value and return the value." That seems unallowed. Instead we must pass up the option to the caller to resolve the future themselves.

Am I missing something here?

Now, I don't think I've ever used them but I've heard of Completers. Is the point of a Completer to allow you to explicitly resolve the Future such that a value can be returned rather than a Future<value>?

1 Answers

You cannot force async code to magically be sync. You need to accommodate this all the way up the return tree. That's what things like FutureBuilder do for you: provide a widget tree to show while the real data is in transit.

Related