Created
October 6, 2016 15:20
-
-
Save juice49/5530926d691aa18629e988bef772dd54 to your computer and use it in GitHub Desktop.
Timeout a JS promise
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
'use strict'; | |
const timeoutPromise = ms => promise => new Promise((resolve, reject) => { | |
const timeout = setTimeout(() => { | |
reject(new PromiseTimeout()); | |
}, ms); | |
promise.then( | |
res => { | |
clearTimeout(timeout); | |
resolve(res); | |
}, | |
err => { | |
clearTimeout(timeout); | |
reject(err); | |
} | |
); | |
}); | |
export default timeoutPromise; | |
export class PromiseTimeout { | |
constructor() { | |
this.name = 'PromiseTimeout'; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment