Skip to content

Instantly share code, notes, and snippets.

@mavame
Last active December 6, 2023 21:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save mavame/adbad3a22cdcaaff314ab8fafd8efaba to your computer and use it in GitHub Desktop.
Save mavame/adbad3a22cdcaaff314ab8fafd8efaba to your computer and use it in GitHub Desktop.
Promise waitAndCatch
/**
* 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);
});
}
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!');
});
@mavame
Copy link
Author

mavame commented Aug 28, 2017

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."

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment