api/index.js
const URL = 'http://10.0.2.2:5000';
const fetching = false;
export default (type, filter, dateFilter, position) => {
if(fetching) return Promise.reject(new Error('Request in progress'));
fetching = true;
return fetch(URL + `/search/${type}/${filter}/${dateFilter}/${position}/0/0`)
.then(response => Promise.all([response, response.json()]))
.catch(err => console.log("error catch search:", err.message))
}
我需要将 fetching 设置为 false,这样我就可以再次调用这个函数,但我不知道该把它放在哪里才能使其工作。 如果我在 then writen 之后和 catch 之前创建另一个 then 像这样:
.then(() => fetching = false)
问题是它返回 false 到调用函数的地方,而不是调用这里的数据:
actions/index.js
getDataApi(type, filter, dateFilter, position)
.then(res => {
if (res !== false) {
if (state.dataReducer.data.length === 0) {
dispatch(getDataSuccess(res[1]))
} else {
dispatch(getDataSuccess(res[1], state.dataReducer.data))
}
}
})
.catch((err) => console.log(9999, err))
所以我的问题是它没有进入 getDataSuccess 因为是 false。我不知道为什么它不能将数据发送到这个函数并且它结束发送 fetching = false 的结果。
最佳答案
您需要另一个.then
这样您就可以重新分配 fetching
response.json()
之后解决了。您可能还应该重新分配 fetching
在 catch
这样即使出现一次错误,将来的请求也是可能的,并且 return false
在 catch
所以.then
之后getDataAPI
将正确忽略失败的请求。另外,使用 let
而不是const
对于 fetching
:
const URL = 'http://10.0.2.2:5000';
let fetching = false;
export default (type, filter, dateFilter, position) => {
if (fetching) return Promise.reject('Request in progress');
fetching = true;
return fetch(URL + `/search/${type}/${filter}/${dateFilter}/${position}/0/0`)
.then(response => Promise.all([response, response.json()]))
.then(([response, responseObj]) => {
fetching = false;
return [response, responseObj];
})
.catch(err => {
console.log("error catch search:", err.message);
fetching = false;
// Choose one, depends what you need.
return false; // If you want to ignore the error and do something in a chained .then()
return Promise.reject(err); // If you want to handle the error in a chained .catch()
})
}
关于javascript - React Native 中的 Promise,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51093024/