Optimal way to make multiple independent requests to server in Dart

╄→гoц情女王★ 提交于 2019-12-01 16:22:35

问题


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?


回答1:


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();
}



回答2:


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



来源:https://stackoverflow.com/questions/50027632/optimal-way-to-make-multiple-independent-requests-to-server-in-dart

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!