I have this code:
void handle(HttpRequest request) async {
request.response.write('Hello');
await Future.delayed(Duration(seconds: 5));
request.response.close();
}
void main() {
var server = await HttpServer.bind(InternetAddress.loopbackIPv4, 8080);
server.listen(handle);
}
And that works properly, all the requests are processed in the same time, now I'm wondering why if I move the response.write
after the Future
, it can only processes only one request at time.
I can reproduce this only in Chromium browser, in Internet Explorer, Edge or CURL requests this doesn't happen.
void handle(HttpRequest request) async {
print('Request on ${Isolate.current.hashCode}');
await Future.delayed(Duration(seconds: 5));
request.response.write('Hello');
request.response.close();
}
Any info if there is a fix(leaving the response.write
after the Future) or any explanation about why this is happening is welcome.
Modified your code like so:
void handle(HttpRequest request) async {
print('A');
await Future.delayed(Duration(seconds: 5));
print('B');
request.response.write('Hello');
print('C');
request.response.close();
}
2 tabs open in chrome, sending requests. One would expect to see A-A-B-C-B-C
in console but in fact it's not so: A-B-C-A-B-C
. @julemand101 pointed out, it has something to do with how Chrome handles connections/caches... Something under the hood. If you disable the cache in dev-tools, you get the result you expect. So it's unrelated to how Dart works and in fact a browser-related oddity.