1
目前,我正在使用express和mongoose處理RESTful-API,現在我遇到了問題。NodeJS:未處理的承諾在方法結束時拒絕
首先,我的方法:
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.
我如何避免這種情況?
感謝您的幫助, felixoi