【问题标题】:React-native Detecting the first successful fetchReact-native 检测第一次成功获取
【发布时间】:2017-02-01 09:05:14
【问题描述】:

在 React-Native 中,我尝试同时获取一堆 IP。第一个用特定状态码回答的就是我要找的那个。这部分发生在应用程序启动时,因此需要尽可能快。使用async库,我的代码是这样的:

// Here an array with a bunch of IPs 
// ...

async.detect(uris, function(uri, callback) {
  // Fetching a specific URL associated with the IP
  fetch(`http://${uri}/productionservice/DataService.svc/`)
  .then((response) => {

  // If the URL answers with a 401 status code I know it's the one I'm looking for
  if(response.status == '401') {
    callback(null, true);
  // Otherwise It's not
  } else {
    callback(null, false)
  }
  })
  .catch((error) => {
    callback(null, false)
  });
}, function(err, result) {

    if(typeof(result)=='undefined') {
      console.log('No result found');
    }
    console.log(result);
});
}

但是,当其中一个测试成功时,我确实得到了结果,但是当没有一个测试成功时,detect 方法会无限期挂起,永远不会让我知道没有任何 IP 会返回我期望的答案。

我的问题是:如何使用 async.detect 和 RN 的 fetch 获取多个链接,如果我的测试成功则获得结果,或者如果没有一个成功则返回 false 语句。

谢谢。

【问题讨论】:

    标签: node.js asynchronous react-native


    【解决方案1】:

    使用 async await 您可以执行以下操作:

    async function detect(uris) {
      const promises = [];
      uris.forEach((uri) => promises.push(fetch(`http://${uri}/productionservice/DataService.svc/`)));
      const responses = await Promise.all(promises);
      for (let i = 0; i < responses.length; i++) {
        if (responses[i] && responses[i].status === '401') {
          return true;
        }
      }
      return false;
    }
    

    【讨论】:

    • 看来responses[i] 正在返回IP,而不是响应,因此该函数无误地返回false。更重要的是如何处理Unhandled promise rejection 警告?它们不断出现。
    • 试一试,忽略catch。
    • 响应应该是每个 uri 的获取结果,这不是你得到的?
    • 在每次迭代时记录responses[i],我只得到我通过的IP,而不是fetch的响应。
    • 抱歉,我马上就看到了你的评论。是的,它奏效了。非常感谢。
    猜你喜欢
    • 2020-01-29
    • 1970-01-01
    • 2018-10-29
    • 2022-01-23
    • 2020-12-29
    • 1970-01-01
    • 1970-01-01
    • 2021-01-13
    • 2019-01-30
    相关资源
    最近更新 更多