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?
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.
You can use Future.wait(...)
to wait for a set of Future
s 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 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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With