Skip to content

Instantly share code, notes, and snippets.

@eschwartz
Created October 10, 2016 16:52
Show Gist options
  • Save eschwartz/6b7da1c00f374a218833e2ec37ceba03 to your computer and use it in GitHub Desktop.
Save eschwartz/6b7da1c00f374a218833e2ec37ceba03 to your computer and use it in GitHub Desktop.
Promise Timeout
/**
* @param {Promise<T>} p
* @param {int} duration Milliseconds until timeout
*
* @returns {Promise<T, TimeoutError>}
*/
function timeout(p, duration) {
const failAfterDuration = new Promise((resolve, reject) => {
const err = Object.assign(new Error(`Timed out after ${duration}ms`), { name: 'TimeoutError' });
setTimeout(() => reject(err), duration);
});
return Promise.race([p, failAfterDuration]);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment