首页 > 解决方案 > 使用异步函数获取 NetInfo

问题描述

我有一个名为的函数hasNetwork,我想返回网络连接状态。

当组件获得焦点时,我尝试使用以下代码并调用函数:

constructor(props) {
    super(props);
    this.props.navigation.addListener('didFocus', () => {

        let hasNetwork = this.hasNetwork();
        console.log(hasNetwork); // Promise {_40: 0, _65: 0, _55: null, _72: null}
    });
}
// ===========================================

// Functions
async hasNetwork() {
    await NetInfo.isConnected.fetch().then(isConnected => {
        if (isConnected) {
            return true;
        } else {
            return false;
        }
    });
}

我希望函数返回 true 或 false 但它返回 Promise !。有什么帮助吗?

标签: react-native

解决方案


由于hasNetworkis also async,您也需要await使用该功能。要制作匿名函数async,只需async在参数之前添加。

此外,由于Network.isConnected.fetch()返回一个无论如何都会返回真/假值的承诺,因此您可以直接使用它而无需使用then.

constructor(props) {
    super(props);
    this.props.navigation.addListener('didFocus', async () => {

        let hasNetwork = await Network.isConnected.fetch();
        console.log(hasNetwork);
    });
}

推荐阅读