Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/36.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Node.js 检测到第一次成功获取时的反应_Node.js_Asynchronous_React Native - Fatal编程技术网

Node.js 检测到第一次成功获取时的反应

Node.js 检测到第一次成功获取时的反应,node.js,asynchronous,react-native,Node.js,Asynchronous,React Native,在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://${u

在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
语句


谢谢。

使用async Wait,您可以按照以下方式进行操作:

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;
}
异步函数检测(URI){ 常量承诺=[]; forEach((uri)=>promises.push(fetch(`http://${uri}/productionservice/DataService.svc/`)); const responses=等待承诺。全部(承诺); for(设i=0;i似乎
响应[i]
返回的是IP,而不是响应,因此函数无误地返回
false
。此外,我如何处理
未处理的拒绝承诺
警告?它们不断出现。请尝试包装它,忽略捕获。响应应该是每个uri的获取结果,这不是您得到的结果?在每次迭代中记录
响应[i]
,我只得到我传递的IP,而不是
获取的响应。抱歉,我看到了您的评论。是的,它成功了。非常感谢。