Created
September 23, 2018 14:41
-
-
Save lekkimworld/8f510e548aa9bb75904f00d48e02aabd to your computer and use it in GitHub Desktop.
Example using Promise.race to timeout if a service lookup takes too long i.e. service not ready maybe due to dependent services
This file contains 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
const lookupService = (name, timeoutService = 100) => { | |
if (!_services[name]) return Promise.reject(`Unknown service <${name}>`) | |
let svc = _services[name] | |
let timeout | |
return Promise.race([ | |
svc.promise, | |
new Promise((resolve, reject) => { | |
timeout = global.setTimeout(() => { | |
reject(new Error(`Time out looking up service <${name}>`)) | |
}, timeoutService) | |
}) | |
]).then(svc => { | |
global.clearInterval(timeout) | |
return svc | |
}).catch(err => { | |
throw err | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment