React-native检测第一次成功获取

时间:2017-02-01 09:05:15

标签: node.js asynchronous react-native

在React-Native中我有一堆IP我试图同时获取。第一个用特定状态代码回答的是我正在寻找的那个。这部分发生在app启动时,因此需要尽可能快。使用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返回我期望的答案。 / p>

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

谢谢。

1 个答案:

答案 0 :(得分:1)

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

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