当我运行此代码时,它会输出starting...
,HTTP repsonse主体,然后finished
,但在Dart进程终止之前似乎等待约5秒。
import 'dart:io';
import 'dart:async';
import 'dart:convert';
Future<String> _sendRequest() async {
var http = new HttpClient();
return http
.postUrl(Uri.parse("https://www.google.com/404"))
.then((HttpClientRequest request) => request.close())
.then((HttpClientResponse response) {
return response.transform(UTF8.decoder).join("");
});
}
main(List<String> args) async {
print("starting...");
print(await _sendRequest());
print("finished");
}
为什么呢?在过去需要很长时间才能结束的print()
之后发生了什么?
答案 0 :(得分:1)
HttpClient
还需要关闭:
Future<String> _sendRequest() async {
var http = new HttpClient();
return http
.postUrl(Uri.parse("https://www.google.com/404"))
.then((HttpClientRequest request) => request.close())
.then((HttpClientResponse response) {
return response.transform(UTF8.decoder).join("");
}).whenComplete(() => http.close()); // <-- ####################
}