首页 > 解决方案 > 如何避免`PromiseRejectionHandledWarning: Promise 拒绝被异步处理`?

问题描述

我的代码收到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);
}

标签: javascripttypescriptpromise

解决方案


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

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

然后在返回之前包装 Promise

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

推荐阅读