我正在使用 fetch 在 react-native 中进行一些 API 调用,有时随机 fetch 不会触发对服务器的请求,并且不会调用我的 then 或 except 块.这是随机发生的,我认为可能存在竞争条件或类似情况.在这样的请求失败后,对同一 API 的请求永远不会被触发,直到我重新加载应用程序.任何想法如何追查这背后的原因.我使用的代码如下.
I am using fetch to make some API calls in react-native, sometimes randomly the fetch does not fire requests to server and my then or except blocks are not called. This happens randomly, I think there might be a race condition or something similar. After failing requests once like this, the requests to same API never get fired till I reload the app. Any ideas how to trace reason behind this. The code I used is below.
const host = liveBaseHost;
const url = `${host}${route}?observer_id=${user._id}`;
let options = Object.assign({
method: verb
}, params
? {
body: JSON.stringify(params)
}
: null);
options.headers = NimbusApi.headers(user)
return fetch(url, options).then(resp => {
let json = resp.json();
if (resp.ok) {
return json
}
return json.then(err => {
throw err
});
}).then(json => json);
Fetch 可能会抛出错误,而您尚未添加 catch 块.试试这个:
Fetch might be throwing an error and you have not added the catch block. Try this:
return fetch(url, options)
.then((resp) => {
if (resp.ok) {
return resp.json()
.then((responseData) => {
return responseData;
});
}
return resp.json()
.then((error) => {
return Promise.reject(error);
});
})
.catch(err => {/* catch the error here *