Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning a String from an async

I want to return a String from an async function but I get a Future What am I doing wrong;

Example

main() {
  String s;
  s = dummy("http://www.google.com");
}

String dummy(String s) {
  String response;
  response = readURL(s);
  return response;
}


Future<String> readURL(String requestString) async {
  String response = await http.read(requestString);
  print(response);
  return response;

}

Error:

type '_Future' is not a subtype of type 'String' of 'response'.

like image 367
user3329151 Avatar asked Nov 24 '15 22:11

user3329151


People also ask

Can an async function return a value?

Async functions enable us to write promise based code as if it were synchronous, but without blocking the execution thread. It operates asynchronously via the event-loop. Async functions will always return a value.

What is async return method?

Async functions always return a promise. If the return value of an async function is not explicitly a promise, it will be implicitly wrapped in a promise.

What return types are allowed for asynchronous methods?

Async Method Return Types There are three return types that a method marked async may have: void. Task. Task< T > for some type T.


1 Answers

A function that's annotated with async will always return a Future.

so when you call readUrl(s) you can await its result.

To use await, the caller (here your main function) has to be marked as async. So the end result could look like this:

main() async {
  String s = await dummy("http://www.google.com");
}

Future<String> dummy(String s) async {
  String response = await readURL(s);
  return (response);
}

Future<String> readURL(String requestString) async {
  String response = await http.read(requestString);
  print(response);
  return(response);
}

The thing to notice here: If you use await in a function, it is now considered as function that returns a Future. So every function you convert to be async will now return a Future.

like image 177
Pacane Avatar answered Oct 02 '22 08:10

Pacane