Created
March 14, 2017 03:30
-
-
Save Calvin-Huang/7f0349df06ce0af7c2ed70dac677472d to your computer and use it in GitHub Desktop.
Warp fetch with promise to reach timeout function.
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
// Reference from @github/fetch issue 175 | |
// https://github.com/github/fetch/issues/175#issuecomment-125779262 | |
function timeoutPromise(ms, promise) { | |
return new Promise((resolve, reject) => { | |
const timeoutId = setTimeout(() => { | |
reject(new Error("promise timeout")) | |
}, ms); | |
promise.then( | |
(res) => { | |
clearTimeout(timeoutId); | |
resolve(res); | |
}, | |
(err) => { | |
clearTimeout(timeoutId); | |
reject(err); | |
} | |
); | |
}) | |
} | |
// Reference from @pepperoni-app-kit | |
// https://github.com/futurice/pepperoni-app-kit/blob/master/src/utils/api.js | |
function timeout(promise, ms) { | |
return new Promise((resolve, reject) => { | |
const timer = setTimeout(() => reject(new Error('timeout')), ms); | |
promise | |
.then(response => { | |
clearTimeout(timer); | |
resolve(response); | |
}) | |
.catch(reject); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment