React Native Fetch: second promise hanging

2019-04-29 06:40发布

问题:

Strange problem with React Native's fetch. It was working previously, not sure what I've changed but it's stopped working.

login(data,success,fail){
    console.log('doing fb login');
    fetch(host+'/api/login?credentials='+data.credentials)
        .then( (response) => {
            console.log('got login response');
            return response.json();
        } )
        .then( json => {
            console.log('got login json');
            if(json.result!='fail'){
                success(json);
            } else {
                fail(json);
            }
            return json;
        })
        .catch((error) => {
          console.warn(error);
        });
}

The issue is I see the first 'got login response' message, but then it just hangs, and nothing happens until I press the screen upon which it fires the 'got login json' and continues as expected.

It's frustrating because this is happening consistently and I can't see why the second .then() isn't firing automatically.

Any help is much appreciated.

EDIT: found a similar question: What could be causing this slow fetch in react native?

seems it is already being looked at: https://github.com/facebook/react-native/issues/6679

Also the behaviour is only seen whne the Chrome debug tools are enabled... interesting

回答1:

response.json() is a promise, not a value. So it won't resolve for you. I would also check result based on response.status instead of json.result because for some case server's response won't convertible to json (401 for example).

.then( (response) => {
   if (response.status >= 200 && response.status < 300) {
      response.json().then((data) => success(data));
   } else {
      fail(response);
   }
})


回答2:

console.log is a blocking statement. A synchrone that stop the code until it is resolved but using with Chrome Debug it can be slow when the tab is not in foreground.