[英]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.