Last active
June 14, 2018 06:20
-
-
Save liuwenzhuang/8686041883c128cf1d9acd02693b8f92 to your computer and use it in GitHub Desktop.
利用Promise.race为fetch提供缺失的timeout的功能,Promise.race的作用是挑选出进行后续then操作的promise,其实每个promise都会被执行,不要在其中做具有side effects的操作
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
function timeoutPromise(timeout) { | |
return new Promise((resolve, reject) => { | |
setTimeout(resolve, timeout); | |
}); | |
} | |
request(url, options, timeout) { | |
const defaultOptions = { | |
credentials: 'include', | |
}; | |
const newOptions = { ...defaultOptions, ...options }; | |
if (newOptions.method === 'POST' || newOptions.method === 'PUT') { | |
if (!(newOptions.body instanceof FormData)) { | |
newOptions.headers = { | |
Accept: 'application/json', | |
'Content-Type': 'application/json; charset=utf-8', | |
...newOptions.headers, | |
}; | |
newOptions.body = JSON.stringify(newOptions.body); | |
} else { | |
// newOptions.body is FormData | |
newOptions.headers = { | |
Accept: 'application/json', | |
...newOptions.headers, | |
}; | |
} | |
} | |
return Promise.race([ | |
fetch(url, newOptions), | |
timeoutPromise(timeout).then(() => { | |
throw new Error('timeout'); | |
}) | |
]) | |
.then(response => { | |
if (newOptions.method === 'DELETE' || response.status === 204) { | |
return response.text(); | |
} | |
return response.json(); | |
}) | |
.catch(err => { | |
return { | |
success: false, | |
message: err.message, | |
}; | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment