在Dart中向服务器发出多个独立请求的最佳方法 [英] Optimal way to make multiple independent requests to server in Dart

查看:207
本文介绍了在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;
}

现在,api调用是一个接一个地进行的。但是api调用彼此独立。最好的实现方法是什么,以避免异步等待地狱?

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?

推荐答案

Günter击败了我几分钟,但是我已经输入了它,所以这里有一个替代方案,它也可以工作,并且避免完全使用'then'。

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

这篇关于在Dart中向服务器发出多个独立请求的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆