Unforgiven
Unforgiven

Reputation: 331

React-native Detecting the first successful fetch

in React-Native I have a bunch of IPs that I try to fetch simultaneously. The first one to answer with a specific status code is the one I am looking for. This part happens at the app startup, so it needs to be as fast as possible. Using the async library, my code is like this:

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

However, when one of the tests succeeds, I do get a result, but when none succeeds, the detect method hangs indefinitely, never letting me know that none of the IPs is returning the answer I expect.

My question is: How, using async.detect and RN's fetch, can I fetch multiple links, get a result if my test succeeds, or a false statement if none of them succeeds.

Thank you.

Upvotes: 0

Views: 41

Answers (1)

yedidyak
yedidyak

Reputation: 1984

Using async await you can do something along these lines:

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

Upvotes: 1

Related Questions