javascript - 如何避免`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);
}
解决方案
我发现了这个问题。在 Jest 中,你不能只用拒绝的承诺来模拟返回值。您需要将其包装在特殊的解决方法中:
const safeReject = p => {
p.catch(ignore=>ignore);
return p;
};
然后在返回之前包装 Promise
const sendNotification = jest.fn();
sendNotification.mockReturnValue(safeReject(Promise.reject(Error('test error'))));
推荐阅读
- ngrx - 在ngrx中使用带有道具的选择器的替代方法是什么
- .net - 缺少 dotnet.exe
- c - 为什么试图尊重 void 指针不起作用?
- python - Python 中没有 sympy.nonlinsolve() 的收敛解决方案
- m3u - 如何定制 m3u 流以获得特定的分辨率或数据速率?
- vue.js - Jest + Vue3 + @Vueform/slider “语法错误:不能在模块外使用导入语句”
- android - 如何在android中以编程方式从后台打开自己的应用程序?
- excel - 为什么 VBA Excel 显示已定义变量的错误 91?
- forms - 替换正文中不需要的字符
- r - 字符串序列以一个正在运行的字符开始,然后是一个数字向量