Respond to native sampling without then calling or catching

I use fetch to call some API calls in a-native reaction, sometimes randomly fetching does not start requests to the server, and mine then or only blocks are not called. This happens randomly, I think it could be a race condition or something like that. After unsuccessful requests once so, requests to one API will never be fired until I restart the application. Any ideas how to trace the cause of 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); 
+8
source share
3 answers

Fetch may cause an error and you have not added a catch block. Try the following:

 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 */}); 

Remember that Promises usually has this format:

 promise(params) .then(resp => { /* This callback is called is promise is resolved */ }, cause => {/* This callback is called if primise is rejected */}) .catch(error => { /* This callback is called if an unmanaged error is thrown */ }); 

I use it that way because I used to run into the same problem.

Let me know if this helps you.

+7
source

Wrap fetch in a try-catch:

 let res; try { res = fetch(); } catch(err) { console.error('err.message:', err.message); } 

If you see a “network failure error”, it’s either CORS or really funny, but it got me in the past, make sure that you are not in airplane mode.

+1
source

I'm stuck with this too, make sure your phone and development code are connected to the same Internet, which worked for me.

0
source

Source: https://habr.com/ru/post/1262301/


All Articles