Skip to content

Commit

Permalink
cancel timeout promise on successful http response #172
Browse files Browse the repository at this point in the history
  • Loading branch information
woodser committed Jan 25, 2024
1 parent 2ee2bcb commit 4579644
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 7 deletions.
25 changes: 25 additions & 0 deletions src/main/ts/common/GenUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1480,5 +1480,30 @@ export default class GenUtils {
}
return undefined;
}

/**
* Resolve the given promise with a timeout.
*
* @param promise the promise to resolve within the timeout
* @param timeoutMs the timeout in milliseconds to resolve the promise
* @return the result of the promise unless error thrown
*/
static async executeWithTimeout(promise, timeoutMs): Promise<any> {
return new Promise((resolve, reject) => {
const timeoutId = setTimeout(() => {
reject('Execution timed out in ' + timeoutMs + ' milliseconds')
}, timeoutMs);
promise.then(
(result) => {
clearTimeout(timeoutId);
resolve(result);
},
(error) => {
clearTimeout(timeoutId);
reject(error);
}
);
});
}
}

8 changes: 1 addition & 7 deletions src/main/ts/common/HttpClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -92,13 +92,7 @@ export default class HttpClient {
// request using fetch or xhr with timeout
let timeout = request.timeout === undefined ? HttpClient.DEFAULT_TIMEOUT : request.timeout === 0 ? HttpClient.MAX_TIMEOUT : request.timeout;
let requestPromise = request.requestApi === "fetch" ? HttpClient.requestFetch(request) : HttpClient.requestXhr(request);
let timeoutPromise = new Promise((resolve, reject) => {
let id = setTimeout(() => {
clearTimeout(id);
reject('Request timed out in '+ timeout + ' milliseconds')
}, timeout);
});
return Promise.race([requestPromise, timeoutPromise]);
return GenUtils.executeWithTimeout(requestPromise, timeout);
}

// ----------------------------- PRIVATE HELPERS ----------------------------
Expand Down

0 comments on commit 4579644

Please sign in to comment.