【问题标题】:How to avoid ` PromiseRejectionHandledWarning: Promise rejection was handled asynchronously`?如何避免`PromiseRejectionHandledWarning: Promise 拒绝被异步处理`?
【发布时间】:2021-12-18 15:25:56
【问题描述】:

我的代码收到PromiseRejectionHandledWarning: Promise rejection was handled asynchronously 警告,它也未通过 Jest 测试。我读过 Promise 拒绝应该在它们定义的地方处理,并且似乎理解逻辑和原因。但我的理解似乎有问题,因为我期望的同步处理仍然会引起警告。 我的打字稿代码如下。 被拒绝的承诺是sendNotification(subscription, JSON.stringify(message))。据我了解,它是使用.catch 调用立即处理的,但可能我遗漏了一些东西。谁能指出我的错误?

private notify(tokens: string[], message: IIterableObject): Promise<any> {
    const promises = [];
    tokens.forEach(token => {
        const subscription = JSON.parse(token);
        this.logger.log('Sending notification to subscription', {subscription, message})
        const result = this.WebPushClient
            .sendNotification(subscription, JSON.stringify(message))
            .catch(e => {
                this.logger.log('Send notification failed, revoking token', {
                    subscription,
                    message,
                    token,
                    e
                })
                return this.revokeToken(token).catch(error => {
                    this.logger.error('Failed to revoke token', {
                        token,
                        error,
                    })
                    return Promise.resolve();
                });
            });
        promises.push(result);
    });

    return Promise.all(promises);
}

【问题讨论】:

    标签: javascript typescript promise


    【解决方案1】:

    我发现了问题。 在 Jest 中,你不能只用拒绝的承诺来模拟返回值。您需要将其包装在特殊的解决方法中:

    const safeReject = p => {
        p.catch(ignore=>ignore);
        return p;
    };
    

    然后在返回之前包装 Promise

    const sendNotification = jest.fn();
    sendNotification.mockReturnValue(safeReject(Promise.reject(Error('test error'))));
    

    【讨论】:

      猜你喜欢
      • 2017-04-16
      • 2020-03-22
      • 2018-10-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-04-26
      • 2018-08-26
      相关资源
      最近更新 更多