簡體   English   中英

反應本機檢測首次成功獲取

[英]React-native Detecting the first successful fetch

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM