Skip to content

Commit

Permalink
fix(web): fix Future already completed error when connectTimeout
Browse files Browse the repository at this point in the history
…was set (#6)

Co-authored-by: ipcjs.mac <gipcjs@gmail.com>
  • Loading branch information
AlexV525 and ipcjs authored Oct 20, 2022
1 parent 256502f commit 2c70f22
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 8 deletions.
28 changes: 21 additions & 7 deletions dio/lib/src/adapters/browser_adapter.dart
Original file line number Diff line number Diff line change
Expand Up @@ -61,12 +61,13 @@ class BrowserHttpClientAdapter implements HttpClientAdapter {
);
});

bool haveSent = false;
Timer? connectTimeoutTimer;

if (options.connectTimeout > 0) {
Future.delayed(Duration(milliseconds: options.connectTimeout)).then(
(value) {
if (!haveSent) {
connectTimeoutTimer = Timer(
Duration(milliseconds: options.connectTimeout),
() {
if (!completer.isCompleted) {
completer.completeError(
DioError(
requestOptions: options,
Expand All @@ -76,20 +77,26 @@ class BrowserHttpClientAdapter implements HttpClientAdapter {
StackTrace.current,
);
xhr.abort();
} else {
// connectTimeout is triggered after the fetch has been completed.
}
},
);
}

int sendStart = 0;
xhr.upload.onProgress.listen((event) {
haveSent = true;
// This event will only be triggered if a request body exists.
if (connectTimeoutTimer != null) {
connectTimeoutTimer!.cancel();
connectTimeoutTimer = null;
}

if (options.sendTimeout > 0) {
if (sendStart == 0) {
sendStart = DateTime.now().millisecondsSinceEpoch;
}
var t = DateTime.now().millisecondsSinceEpoch;
print(t - sendStart);
final t = DateTime.now().millisecondsSinceEpoch;
if (t - sendStart > options.sendTimeout) {
completer.completeError(
DioError(
Expand All @@ -111,6 +118,11 @@ class BrowserHttpClientAdapter implements HttpClientAdapter {

int receiveStart = 0;
xhr.onProgress.listen((event) {
if (connectTimeoutTimer != null) {
connectTimeoutTimer!.cancel();
connectTimeoutTimer = null;
}

if (options.receiveTimeout > 0) {
if (receiveStart == 0) {
receiveStart = DateTime.now().millisecondsSinceEpoch;
Expand All @@ -136,6 +148,7 @@ class BrowserHttpClientAdapter implements HttpClientAdapter {
});

xhr.onError.first.then((_) {
connectTimeoutTimer?.cancel();
// Unfortunately, the underlying XMLHttpRequest API doesn't expose any
// specific information about the error itself.
completer.completeError(
Expand All @@ -150,6 +163,7 @@ class BrowserHttpClientAdapter implements HttpClientAdapter {

cancelFuture?.then((err) {
if (xhr.readyState < 4 && xhr.readyState > 0) {
connectTimeoutTimer?.cancel();
try {
xhr.abort();
} catch (e) {
Expand Down
4 changes: 3 additions & 1 deletion example_flutter_app/lib/http.dart
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import 'package:dio/dio.dart';

var dio = Dio();
var dio = Dio(BaseOptions(
connectTimeout: 3000,
));

0 comments on commit 2c70f22

Please sign in to comment.