这就是我要做的:
import 'whatwg-fetch';
function fetchVehicle(id) {
return dispatch => {
return dispatch({
type: 'FETCH_VEHICLE',
payload: fetch(`http://swapi.co/api/vehicles/${id}/`)
.then(status)
.then(res => res.json())
.catch(error => {
throw(error);
})
});
};
}
function status(res) {
if (!res.ok) {
return Promise.reject()
}
return res;
}
编辑:承诺不会被拒绝,这就是我想要弄清楚的。
我正在用这个获取polyfill https://github.com/github/fetch在 Redux 中redux-promise-中间件 https://github.com/pburtchaell/redux-promise-middleware.
Fetch https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch当网络错误发生时,promise 只会拒绝并返回 TypeError。由于 4xx 和 5xx 响应不是网络错误,因此没有什么可捕获的。您需要自己抛出错误才能使用Promise#catch
.
A 获取响应 https://developer.mozilla.org/en-US/docs/Web/API/Response方便地供应ok https://developer.mozilla.org/en-US/docs/Web/API/Response/ok,它告诉您请求是否成功。像这样的事情应该可以解决问题:
fetch(url).then((response) => {
if (response.ok) {
return response.json();
}
throw new Error('Something went wrong');
})
.then((responseJson) => {
// Do something with the response
})
.catch((error) => {
console.log(error)
});
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)