Last active
January 4, 2018 15:39
-
-
Save hanbzu/47b7724413cb4875361325267e3c59ea to your computer and use it in GitHub Desktop.
Promises that time out
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
// 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