Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Optimal way to make multiple independent requests to server in Dart

I want to make to multiple requests to same server in an optimal way. So I have

Future<List<Item>> getAllItems() async {
    var client = new http.Client();
    List<String> itemsIds = ['1', '2', '3']; //different ids
    List<Item> itemList = [];
    for (var item in itemsIds) {
      //make call to server eg: 'sampleapi/1/next' etc
      await client.get('sampleapi/' + item + '/next').then((response) {
        //Do some processing and add to itemList

      });
    }
    client.close();
    return itemList;
}

Now, the api calls are made one after other. But the api calls are independent of each other. Whats the best way to implement so as to avoid the async await hell?

like image 839
Sabith Avatar asked Apr 25 '18 16:04

Sabith


People also ask

How do I handle multiple API requests?

If you need to make multiple API requests, you can send these API requests concurrently instead of sending them one by one. Sometimes, we need to make multiple API calls at once. For example, let's say we have an array, and we want to make an API request for each element of that array.


2 Answers

You can use Future.wait(...) to wait for a set of Futures to complete:

Future<List<Item>> getAllItems() async {
    var client = new http.Client();
    List<String> itemsIds = ['1', '2', '3']; //different ids

    return Future.wait<Item>(['1', '2', '3'].map((item) =>
      client.get('sampleapi/' + item + '/next').then((response) {
        //Do some processing and add to itemList
        return foo; // some Item that is the result of this request 
      });
    );
}

See also https://api.dartlang.org/stable/1.24.3/dart-async/Future/wait.html

like image 181
Günter Zöchbauer Avatar answered Oct 21 '22 08:10

Günter Zöchbauer


Günter beat me to it by a couple minutes, but I've already typed it out so here's a slight alternative which would also work and avoids using 'then' completely.

Future<List<Item>> getAllItems() async {
  var client = new Client();
  List<String> itemsIds = ['1', '2', '3']; //different ids

  List<Response> list = await Future.wait(itemsIds.map((itemId) => client.get('sampleapi/$itemId/next')));

  return list.map((response){
    // do processing here and return items
    return new Item();
  }).toList();
}
like image 28
rmtmckenzie Avatar answered Oct 21 '22 08:10

rmtmckenzie