Skip to content

Instantly share code, notes, and snippets.

@minedun6
Created March 3, 2018 13:46
Show Gist options
  • Save minedun6/5a310dc684d1ebd5111cac8d79cfaba6 to your computer and use it in GitHub Desktop.
Save minedun6/5a310dc684d1ebd5111cac8d79cfaba6 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!');
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment