【问题标题】:Possible unhandled promise rejection with Request timeout请求超时可能未处理的承诺拒绝
【发布时间】:2021-12-28 11:44:10
【问题描述】:

我在我的 React Native 应用程序中调用了一个函数,它抛出了如下错误:Possible Unhandled Promise Rejection (id: 44): "Request timeout"。现在我说的函数是这样的:

    public async login(): Promise<any> {
        try{
            const manufacturer = await getManufacturer();
            return this.client
                .send({
                    command: 'handshake',
                    username: '',
                    password: '',
                    action: 'get',
                    auth_serial: this.token,
                    manufacturer: manufacturer,
                    version: this.transport?.version,
                    os_detail: getSystemName().concat(' ', getSystemVersion()),
                })
                .then(
                    async (result) => {
                        if (
                            result.param === 'authenticated' &&
                            result.auth_hash !== ''
                        ) {
                            this.onLogin(result);
                        }
                        return result;
                    },
                    async (reason) => {
                        await this.logout();
                        throw reason;
                    },
                );
        }catch(err) {
            console.log('Error occured',err);
        }
        
    }

我什至将它包装在 try/catch 块中。为什么它仍然抛出该错误?

【问题讨论】:

  • 您正在使用async/await 语法。为所有人使用它。 this.client.send(..) 返回一个 Promise,等待它并将结果保存在 result 中。喜欢const result = await this.client.send({...});

标签: javascript reactjs react-native


【解决方案1】:

异步函数隐式返回一个带有函数结果的承诺,你不应该混合使用 .then 和 async/await 语法,因为它很难阅读。 (可能也会混淆你的 linter)

public async login() {
try {
    const manufacturer = await getManufacturer();
    const result = await this.client.send({
        command: 'handshake',
        username: '',
        password: '',
        action: 'get',
        auth_serial: this.token,
        manufacturer: manufacturer,
        version: this.transport?.version,
        os_detail: getSystemName().concat(' ', getSystemVersion()),
    })
    if (
        result.param === 'authenticated' &&
        result.auth_hash !== ''
    ) {
        this.onLogin(result);
    }
    return result;
} catch(err) {
    console.log('Error',err);
    await this.logout();
}

此外,您将返回 this.client.send,因此无论您在何处使用登录功能,如果您想保持代码不变,您可能必须在此处添加一个 catch。

【讨论】:

  • 做了这个并且仍然抛出同样的错误@MichaelCohen
  • @TanmoySarker 那么你应该在你使用登录功能的地方添加try catch。我真的帮不上忙,因为我看不到你把这个函数放进去的整个班级
猜你喜欢
  • 2016-11-24
  • 2017-08-02
  • 1970-01-01
  • 1970-01-01
  • 2016-12-15
  • 1970-01-01
  • 2023-01-04
  • 2020-07-12
  • 1970-01-01
相关资源
最近更新 更多