Last active
January 28, 2018 10:54
-
-
Save mgtitimoli/973b96464c74a36b504ccfa025b656f6 to your computer and use it in GitHub Desktop.
A clean timeout implementation using promises + bonus track: waitUntil
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
import createDeferred from "./createDeferred"; | |
const awaitTimeout = (miliseconds, onTimeout) => { | |
const deferred = createDeferred(); | |
const timeoutId = setTimeout( | |
() => onTimeout(deferred.resolve, deferred.reject), | |
miliseconds | |
); | |
const createClearer = resolver => value => { | |
clearTimeout(timeoutId); | |
resolver(value); | |
}; | |
return { | |
promise: deferred.promise, | |
reject: createClearer(deferred.reject), | |
resolve: createClearer(deferred.resolve), | |
}; | |
}; | |
export default awaitTimeout; |
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
const createDeferred = () => { | |
const deferred = {}; | |
deferred.promise = new Promise((resolve, reject) => { | |
deferred.resolve = resolve; | |
deferred.reject = reject; | |
}); | |
return deferred; | |
}; | |
export default createDeferred; |
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
import awaitTimeout from "./waitUntil"; | |
import waitUntil from "./waitUntil"; | |
const getUserStub = id => awaitTimeout(5000, resolve => resolve({ | |
id, | |
name: "John Doe", | |
}); | |
waitUntil(2000, getUserStub(10)); // it will timeout rejecting promise with Error("Timeout with 2000 ms") |
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
import awaitTimeout from "./await-timeout"; | |
const waitUntil = (miliseconds, promise) => { | |
const timeout = awaitTimeout( | |
miliseconds, | |
(_, reject) => new Error("Timeout with " + miliseconds + " ms"); // gist doesn't support template literals :| | |
); | |
promise.then(timeout.resolve, timeout.resolve); | |
return Promise.race([ | |
promise, | |
timeout, | |
]); | |
}; | |
export default waitUntil; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment