实现方式
一、github/fetch#20
var p = Promise.race([
fetch('/resource-that-may-take-a-while'),
new Promise(function (resolve, reject) {
setTimeout(() => reject(new Error('request timeout')), 5000)
})
])
p.then(response => console.log(response))
p.catch(error => console.log(error))
var req = new Request(url, option);
req.fetch().then((res) => {
console.log(res.status);
}).catch((err) => {
console.error(err); // this will also happen in `abort()` request
});
// timeout a request
setTimeout(function() {
req.abort(); // reject the fetching process
}, 1000);
const oldfetch = fetch;
fetch = function(input, opts) {
return new Promise((resolve, reject) => {
setTimeout(reject, opts.deadline);
oldfetch(input, opts).then(resolve, reject);
});
}