Last active
June 23, 2022 12:09
-
-
Save portothree/9058f6d1d07940c71848e30c6957bdf4 to your computer and use it in GitHub Desktop.
Timeout an Promise
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
| function timeoutPromise(prom, time) { | |
| let timer; | |
| return Promise.race([ | |
| prom, | |
| new Promise( | |
| (_r, rej) => | |
| (timer = setTimeout(rej, time, new Error("Promise timed out"))) | |
| ), | |
| ]).finally(() => clearTimeout(timer)); | |
| } | |
| async function customPromise() { | |
| await new Promise((res) => setTimeout(res, 500)); | |
| } | |
| async function main() { | |
| try { | |
| await timeoutPromise(customProm(), 100); | |
| } catch (error) { | |
| console.log(error); | |
| } | |
| } | |
| main(); // Error: Promise timed out |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment