Skip to content

Instantly share code, notes, and snippets.

@minedun6
Created September 23, 2018 07:13
Show Gist options
  • Save minedun6/0f36823f070d4a0e2bb2938877d68039 to your computer and use it in GitHub Desktop.
Save minedun6/0f36823f070d4a0e2bb2938877d68039 to your computer and use it in GitHub Desktop.
Promise.takeAtLeast
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!');
});
// Creates a new promise that automatically resolves after some timeout:
Promise.delay = function (time) {
return new Promise((resolve, reject) => {
setTimeout(resolve, time)
})
}
// Throttle this promise to resolve no faster than the specified time:
Promise.prototype.takeAtLeast = function (time) {
return new Promise((resolve, reject) => {
Promise.all([this, Promise.delay(time)]).then(([result]) => {
resolve(result)
}, reject)
})
}
// Make sure this doesn't resolve for at least 300ms, useful for things like
// keeping a loading spinner on screen just long enough to not look janky:
axios.post(`/published-products`, payload)
.takeAtLeast(300)
.then(response => {
this.loading = false
// ...
})
.catch(response => {
this.loading = false
// ...
})
/**
* 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);
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment