Last active
December 6, 2023 21:52
-
-
Save mavame/adbad3a22cdcaaff314ab8fafd8efaba to your computer and use it in GitHub Desktop.
Promise waitAndCatch
This file contains 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
/** | |
* Wait for a specified number of milliseconds. If a promise hasn't resolved, reject it. | |
* This is a necessary replacement in some cases since cancellable promises aren't a thing | |
* and is helpful if you want to wait _no longer than_ a specified amount of time. | |
* @param {int} time Amount of time to wait before resolving arbitrarily. | |
* @param {function} fn That returns a Promise. It will be run one tick before the timer starts. | |
* @return {Promise} | |
*/ | |
export function waitAndCatch(time, fn) { | |
return new Promise((resolve, reject) => { | |
fn().then(resolve).catch(reject); | |
delay(time).then(reject); | |
}); | |
} | |
// Creates a new promise that automatically resolves after some timeout | |
export function delay(time) { | |
return new Promise((resolve, reject) => { | |
setTimeout(resolve, time); | |
}); | |
} |
This file contains 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
import { delay, waitAndCatch } from 'promise-wait-and-catch'; | |
// mock something that takes some time | |
function doSomethingThatTakesAWhile() { | |
// a more useful example would be calling an API, but in this case we'll just arbitrarily | |
// run a 3000 millisecond task. | |
return delay(3000); | |
} | |
waitAndCatch(2000, doSomethingThatTakesAWhile) | |
.then(() => { | |
console.log('Finished in time.'); | |
}) | |
.catch(() => { | |
console.log('Took too long!'); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You should see "Took too long!" in the console. If you decrease the time
doSomethingThatTakesAWhile
takes to run to under 2000ms, you will see "Finished in time."