Forked from wilmanbarrios/promise-take-at-least.js
Created
September 21, 2020 09:11
-
-
Save minedun6/4b002a736734cb960263339b196935ae to your computer and use it in GitHub Desktop.
Promise.takeAtLeast
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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 | |
// ... | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment