Created
October 10, 2016 16:52
-
-
Save eschwartz/6b7da1c00f374a218833e2ec37ceba03 to your computer and use it in GitHub Desktop.
Promise Timeout
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /** | |
| * @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