React Native Fetch:第二个承诺挂起

React Native Fetch: second promise hanging

本文关键字:承诺 挂起 第二个 Native Fetch React      更新时间:2023-09-26

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 native中的获取速度缓慢?

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

此外,只有在启用Chrome调试工具时才能看到这种行为。。。有趣的

response.json()是一个承诺,而不是一个值。所以它不会为你解决。我也会根据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 Debug一起使用时,当选项卡不在前台时,它可能会很慢。