Skip to content

Instantly share code, notes, and snippets.

@Calvin-Huang
Created March 14, 2017 03:30
Show Gist options
  • Save Calvin-Huang/7f0349df06ce0af7c2ed70dac677472d to your computer and use it in GitHub Desktop.
Save Calvin-Huang/7f0349df06ce0af7c2ed70dac677472d to your computer and use it in GitHub Desktop.
Warp fetch with promise to reach timeout function.
// 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