Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

This comment has been minimized.

Copy link
Owner 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
You can’t perform that action at this time.