Skip to content

Instantly share code, notes, and snippets.

@evanhsu
Last active April 10, 2018 17:17
Show Gist options
  • Save evanhsu/2fb9485252ef3e5efce662467f491ec8 to your computer and use it in GitHub Desktop.
Save evanhsu/2fb9485252ef3e5efce662467f491ec8 to your computer and use it in GitHub Desktop.
Create a js promise with a timeout
/**
* Creates a promise that rejects after the specified amount of time.
* This can be used with the Promise.race() method to set a timeout on a different Promise:
*
* Promise.race([
* fetchDataSlowly(),
* timeoutThenReject(5000)
* ]);
*
* @param durationMillis Number of milliseconds to wait before resolving with a rejection.
* @returns {Promise}
*/
timeoutThenReject(durationMillis) {
return new Promise((resolve, reject) => {
let timeoutId = setTimeout(() => {
clearTimeout(timeoutId);
reject('Timed out');
}, durationMillis);
});
}
/**
* Apply a timeout to an existing promise. If the promise doesn't resolve before the timeout, then
* this `promiseWithTimeout` promise will resolve with a rejected status.
*
* @param externalPromise A promise that won't be allowed to run longer than the specified timeout.
* @param durationMillis Number of milliseconds to wait before resolving with a rejection.
* @returns {Promise}
**/
export default promiseWithTimeout(externalPromise, durationMillis) {
return Promise.race([
externalPromise,
timeoutThenReject(durationMillis),
]);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment