I'm just trying to fetch data using Fetch API . Here's my code
function status(response) {
return response.json().then( data => {
if(response === 200) {
return data
}else if(response.status === 400){
let message = data.error.error.error[0]
return Promise.reject({status: response.status, message});
}else if(response.status === 401){
let message = data.message
return Promise.reject({status: response.status, message});
}else{
return Promise.reject({status: response.status, data});
}
})
}
export function getAgenda(limit, offset, status){
return (dispatch)=>{
dispatch({
type: 'FETCH_AGENDA_REQUEST'
})
const token = loadCred().token
api.fetchAgenda(limit, offset, status, token)
.then(status)
.then(function(data){
console.log(data) // this is printed in console
dispatch({
type: 'FETCH_AGENDA_SUCCESS',
payload: {
...data,
totalPages: Math.ceil(data.totalRows / limit)
}
})
}).catch(function(error) {
console.log(error) // not this one
dispatch({
type: 'FETCH_AGENDA_ERROR',
payload: {
error
}
});
})
}
}
Since Fetch API consider 400++ as a resolved Promise, I tried to filter them first using Status function. But it turned out that error 401 considered a Resolved rather than Rejected. I tried to check but error in console wasn't printed by catch.
答案 0 :(得分:0)
您的状态函数可能会返回已解决的承诺或以其他方式拒绝承诺(抛出错误会使catch语句阻止它)。
function main() {
// call fetchAgenda api
api.fetchAgenda(
// what you are doing here
// ...
// return a response object
).then(
response => status(response)
// resolved promise returned by status call
).then(
data => console.log(data);
// rejected promise returned by status call
).catch(
error => console.log(error);
);
}
function status(response) {
// if response is ok (200 - 299) or is less than 400
if (response.ok || response.status < 400) {
// it's good, convert it into json
return response.json();
}
else {
// response isn't fine, reject promise...
return Promise.reject(response);
// ... or throw an error
// return throw Error(response);
}
}