React Native Fetch:第二个Promise挂起

IT技术 javascript reactjs promise react-native fetch-api
2021-05-23 16:54:03

React Native 的 fetch 有一个奇怪的问题。它以前工作过,不确定我改变了什么,但它停止工作了。

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

问题是我看到了第一个“获得登录响应”消息,但它只是挂起,直到我按下屏幕,它会触发“获得登录 json”并按预期继续。

这令人沮丧,因为这种情况一直在发生,我不明白为什么第二个 .then() 没有自动触发。

任何帮助深表感谢。

编辑:发现了一个类似的问题:什么可能导致本机react缓慢?

似乎已经在看:https : //github.com/facebook/react-native/issues/6679

此外,只有在启用 Chrome 调试工具时才能看到该行为......很有趣

2个回答

response.json() 是一个 promise,而不是一个值。所以它不会为你解决。我还会根据 response.status 而不是 json.result 检查结果,因为在某些情况下,服务器的响应不会转换为 json(例如 401)。

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

console.log 是一个阻塞语句。停止代码直到解决它的同步,但使用Chrome调试时,当标签不在前台时,它可能会慢。