14

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?

Sabith
  • 185
  • 2
  • 3
  • 10

2 Answers2

24

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

Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
  • i am making multiple calls to same server using different future methods but it returns me empty body id i make single http call it works fine – HaSnen Tai Apr 10 '19 at 11:51
  • 1
    Not sure. Perhaps you expect one requests to be made only after the previous one completed. They are made concurrently. If one request depends on another one to be completed previously, this won't work. If this is not the case in your situation, I don't know what causes it. – Günter Zöchbauer Apr 10 '19 at 12:53
  • let me try the above solution hope it will work for and thanks for the reply – HaSnen Tai Apr 11 '19 at 04:38
  • @GünterZöchbauer can store these 3 APIs data on local 3 tables DB using SQLite? – user9139407 Jun 20 '19 at 07:23
  • Not sure what you mean with "this 3 APIs`, but sure, why not? – Günter Zöchbauer Jun 20 '19 at 08:43
15

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();
}
rmtmckenzie
  • 37,718
  • 9
  • 112
  • 99