当前,我使用http
,我发现一种方法可以一次发送多个请求以使用axios进行响应。
axios.all([
axios.get('http://google.com'),
axios.get('http://apple.com')
])
.then(axios.spread((googleRes, appleRes) => {
// do something with both responses
});
就像这样,一次发送多个请求有什么办法吗?
答案 0 :(得分:0)
import 'dart:async';
import 'package:http/http.dart' as http;
Future<void> main() async {
var requests = <Future<http.Response>>[];
requests.add(http.get('http://google.com'));
requests.add(http.get('http://apple.com'));
var responses = await Future.wait(requests);
for (var result in responses) {
if (result.statusCode != 200) {
print('Something went wrong');
break;
}
}
}
答案 1 :(得分:0)
@mezoni答案是正确的。但这也减少了缓存代码。
import 'dart:async';
import 'dart:convert';
import 'package:http/http.dart' as http;
void main() async {
final urlList = ['http://google.com', 'http://apple.com'];
final responses = await Future.wait(
urlList.map((String url) {
return http.get(url);
}),
);
final List<Map<String, dynamic>> caches = responses.map((response) {
return json.decode(response.body);
});
}