Poperton
Poperton

Reputation: 1746

efficient async function that needs result from another async function in dart (http client)

From here Dart - Request GET with cookie we have this example of doing a get request with dart's built in HTTP library:

exampleCall() {
  HttpClient client = new HttpClient();
  HttpClientRequest clientRequest =
      await client.getUrl(Uri.parse("http: //www.example.com/"));
  clientRequest.cookies.add(Cookie("sessionid", "asdasdasqqwd"));
  HttpClientResponse clientResponse = await clientRequest.close();
}

As you can see, multiple awaits are needed. Which means that if I try to do multiple concurrent exampleCall calls, they won't happen at the same time.

I cannot return a future because I must wait the client.getUrl() in order to do the clientResponse.

I also couldn't find a good alternative to use cookies on http calls. Dio seems to only support storing cookies from the server. Anyways, I'd like to know how to do in this way, but if there's a better way I'd like to know.

Upvotes: 0

Views: 99

Answers (1)

julemand101
julemand101

Reputation: 31299

As you can see, multiple awaits are needed. Which means that if I try to do multiple concurrent exampleCall calls, they won't happen at the same time.

Not really sure what you mean here. Dart is single threaded so the concept of things happen "at the same time" is a little vauge. But if you follow the example later you should be able to call exampleCall() multiple times without the need of waiting on each other.

I cannot return a future because I must wait the client.getUrl() in order to do the clientResponse.

Yes you can if you mark the method as async:

import 'dart:convert';
import 'dart:io';

Future<List<String>> exampleCall() async {
  final client = HttpClient();
  final clientRequest =
      await client.getUrl(Uri.parse("http://www.example.com/"));
  clientRequest.cookies.add(Cookie("sessionid", "asdasdasqqwd"));
  final clientResponse = await clientRequest.close();

  return clientResponse
      .transform(utf8.decoder)
      .transform(const LineSplitter())
      .toList();
}

The whole point of async methods is the ability to easily bundle multiple asynchronous calls into a single Future. Notice, that async methods must always return a Future but your return statement should not necessarily return a Future object (if you return a normal object, it will automatically be packed into a Future).

I also couldn't find a good alternative to use cookies on http calls. Dio seems to only support storing cookies from the server. Anyways, I'd like to know how to do in this way, but if there's a better way I'd like to know.

Not really sure about the whole cookie situation. :)

Upvotes: 1

Related Questions