我希望以最佳方式向同一服务器发出多个请求。所以我有
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调用是相互独立的。什么是最好的实施方式,以避免异步等待地狱?
答案 0 :(得分:7)
您可以使用Future.wait(...)
等待一组Future
完成:
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
});
);
}
另见https://api.dartlang.org/stable/1.24.3/dart-async/Future/wait.html
答案 1 :(得分:5)
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();
}