Skip to content

Instantly share code, notes, and snippets.

@adamwathan
Last active February 26, 2023 14:25
Show Gist options
  • Save adamwathan/babd10ed0e971404c5d8a86358d01b61 to your computer and use it in GitHub Desktop.
Save adamwathan/babd10ed0e971404c5d8a86358d01b61 to your computer and use it in GitHub Desktop.
Promise.takeAtLeast
// 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
// ...
})
@engram-design
Copy link

This is great, but can't seem to get it to work in IE Edge! "Object doesn't support property or method 'takeAtLeast'" @adamwathan

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