Skip to content

Instantly share code, notes, and snippets.

@hanbzu
Last active January 4, 2018 15:39
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 hanbzu/47b7724413cb4875361325267e3c59ea to your computer and use it in GitHub Desktop.
Save hanbzu/47b7724413cb4875361325267e3c59ea to your computer and use it in GitHub Desktop.
Promises that time out
// A higher order function that makes a promise time out after X ms
const timeoutAfter = ms => promise => {
const rejectOnTimeout = new Promise((resolve, reject) =>
setTimeout(() => reject(new Error(`Timed out after ${ms} ms waiting for promise to resolve`)), ms)
)
return Promise.race([promise, rejectOnTimeout])
}
// Here's how you use it
const myLoooongPromise = new Promise((resolve, reject) =>
setTimeout(() => resolve('Finally doneeee!'), 1000000000)
)
timeoutAfter(500)(myLoooongPromise)
.then(console.log)
.catch(console.error)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment