目前,我正在使用Express和Mongoose开发RESTful-API,现在遇到了问题。
首先,我的方法:
public create() : Promise<UserDocument> {
return new Promise((user) => {
User.exists(this.username).then((exists) => {
if (exists) {
throw Errors.mongoose.user_already_exists;
} else {
UserModel.create(this.toIUser()).then((result) => {
user(result);
}).catch(() => {
throw Errors.mongoose.user_create
});
}
}).catch((error) => {
throw error;
})
});
}
执行此方法时,出现未处理的诺言拒绝。即使我在执行以下方法时处理错误,也会发生这种情况:
User.fromIUser(user).create().then(() => {
return response.status(200).send({
message: "Created",
user
});
}).catch((error) => {
return response.status(500).send({
message: error
});
});
完整的堆栈跟踪:
(node:23992) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): User already exists
(node:23992) 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.
我如何避免这种情况?
谢谢你的帮助,
费利克索
最佳答案
我找到了解决方案!只需使用“解决,请求”即可创建承诺。
现在是我的方法:
public create() : Promise<any> {
return new Promise((resolve, reject) => {
User.exists(this.username).then((exists) => {
if (exists) {
reject( Errors.mongoose.user_already_exists);
} else {
UserModel.create(this.toIUser()).then((result) => {
resolve(result);
}).catch(() => {
reject(Errors.mongoose.user_create);
});
}
}).catch((error) => {
reject(error);
})
})
}
如果现在调用该方法,则可以使用
catch()
方法,一切正常!这样称呼它:User.fromIUser(user).create().then((user) => {
return response.status(200).send({
message: "Created",
user
});
}).catch((error) => {
return response.status(500).send({
message: error
})
})