I want to check if the server my app is trying reach is reachable (When internet is reachable) before making a request.
I am using Fetch API and right now I am using function timeout which works well but my question is is there any way by which I can check if server is reachable.
I tried using all-reacheable npm package and added following code but I do not get any call back response.
isReachable([
'http://aposddasd.com',
'http://google.com'
], (err, reachable, host) => {
console.log('Server is' + reachable); //=> false
console.log('App log' + host); //=> 'http://aposddasd.com'
});
Can you help me with what is best way to achieve this?
You can use a Promise.race()
which will return the first promise to resolve or reject - they're pretty awesome actually! Checkout the docs here:
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise/race
Here's a simple function which times out after 3ms - it's using httpbin to simulate a delay of 5s:
const isAvailable = () => {
const timeout = new Promise((resolve, reject) => {
setTimeout(reject, 300, 'Request timed out');
});
const request = fetch('https://httpbin.org/delay/5');
return Promise
.race([timeout, request])
.then(response => alert('It worked :)'))
.catch(error => alert('It timed out :('));
}
isAvailable();
Checkout the fiddle here: https://jsfiddle.net/edcs/8Lcg8a8j/10/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With