Skip to content

Instantly share code, notes, and snippets.

@challet
Created December 25, 2019 22:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save challet/76955d6d3ccb5787cea0979c5385f0d4 to your computer and use it in GitHub Desktop.
Save challet/76955d6d3ccb5787cea0979c5385f0d4 to your computer and use it in GitHub Desktop.
A promise that settles *at least* after the given delay
// A promise that won't resolve or reject before the delay
// Might be used for giving time for an UI update & reset to be seen
const discernablePromise = (genuine, delay = discernablePromise.SENSIBLE_DELAY) => {
return new Promise((resolve, reject) => {
Promise.allSettled([
genuine,
new Promise(resolve => setTimeout(resolve, delay))
])
.then(results => {
if (results[0].status === 'fulfilled') {
resolve(results[0].value);
} else {
reject(results[0].reason);
}
});
});
};
Object.defineProperty(discernablePromise, 'SENSIBLE_DELAY', { value: 150 });
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment