【发布时间】:2021-03-23 07:08:34
【问题描述】:
我收到此错误:
(node:9868) UnhandledPromiseRejectionWarning: #<Object>
(node:9868) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:9868) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code
我正在使用如下所示的快速错误处理程序包装 create 方法:
export const errorHandler = (callback: any) => {
return (req: Request, res: Response, next: NextFunction) => {
callback(req, res, next).catch(next);
};
};
当我尝试这样做时:
async create(entity: T){
this._model
.findOne({ name: (entity as any).name })
.then((res) => {
if (res) {
throw Exceptions.ENTITY_EXISTS; // doesnt work
}
})
}
但是,当我将其更改为异步等待时,它可以正常工作
async create(entity: T) {
const res = await this._model.findOne({ name: (entity as any).name });
if (res) throw Exceptions.ENTITY_EXISTS;
}
当我尝试做而不是 throw Promise.reject(Exceptions.ENTITY_EXISTS) 时,它也抛出了同样的错误。
谁能解释一下这三者之间的区别,以及为什么只有异步等待起作用?
【问题讨论】:
标签: javascript node.js ecmascript-6 es6-promise