如何在没有网络的情况下进入Fetch API中的catch方法?
How to get in catch method in Fetch API when there is no internet?
我正在使用 Fetch API 处理请求,我想在禁用互联网时处理错误。但是我在 THEN 函数中没有得到任何响应,在 CATCH 函数中也没有错误消息。我该如何处理这个问题。我正在尝试在 React Native 中这样做。先谢谢你
检查 NetInfo
API available with React Native. You should be able to use the isConnected 方法以在发出请求之前检查它是否已连接到互联网。
import {NetInfo} from 'react-native'
NetInfo.isConnected.fetch().then(isConnected => {
console.log('First, is ' + (isConnected ? 'online' : 'offline'));
if (isConnected) {
fetch(...)
}
});
我能够复制 catch
在 WiFi 关闭时永远不会被调用。如果请求从不 returns 实施这样的解决方案以手动抛出错误可能是解决此问题的方法。 See this discussion on handling Timeouts with Fetch.
let test = () => {
return new Promise((resolve, reject) => {
let id = setTimeout(() => reject('Timeout'),3000)
fetch('https://swapi.co/api/people/1/')
.then(res => {
resolve(res)
clearTimeout(id)
})
.catch(err => {
reject(err)
clearTimeout(id)
})
})
}
test()
.then(() => console.log('************Success'))
.catch(() => console.warn('*************Error'))
我正在使用 Fetch API 处理请求,我想在禁用互联网时处理错误。但是我在 THEN 函数中没有得到任何响应,在 CATCH 函数中也没有错误消息。我该如何处理这个问题。我正在尝试在 React Native 中这样做。先谢谢你
检查 NetInfo
API available with React Native. You should be able to use the isConnected 方法以在发出请求之前检查它是否已连接到互联网。
import {NetInfo} from 'react-native'
NetInfo.isConnected.fetch().then(isConnected => {
console.log('First, is ' + (isConnected ? 'online' : 'offline'));
if (isConnected) {
fetch(...)
}
});
我能够复制 catch
在 WiFi 关闭时永远不会被调用。如果请求从不 returns 实施这样的解决方案以手动抛出错误可能是解决此问题的方法。 See this discussion on handling Timeouts with Fetch.
let test = () => {
return new Promise((resolve, reject) => {
let id = setTimeout(() => reject('Timeout'),3000)
fetch('https://swapi.co/api/people/1/')
.then(res => {
resolve(res)
clearTimeout(id)
})
.catch(err => {
reject(err)
clearTimeout(id)
})
})
}
test()
.then(() => console.log('************Success'))
.catch(() => console.warn('*************Error'))