我有一个带有实例函数的类
// file1.js
export default class User {
constructor() {
this.userSchema = new Schema({
username: String,
password: String,
});
this.usermodel = Mongo.getModel('user', this.userSchema);
}
signUp({username, password}) {
var user = new this.usermodel({username: username,password: password});
this.usermodel.findOne({username: username}).exec((err, userresult) => {
if (err) {
/////////////// **LOCATION 1**: throw error that can be
} else {
if(userresult) { // one user case so
/////**LOCATION 2**: throw new Error("User with this Username already exists !. Please try a new Username.");
} else { // null case
return new DbResult({});
}
}
})
}
}
我称之为file1的signUp的另一个文件file2。
// file2.js
const user = new User();
try {
user.signUp({username: request.body.username, password: request.body.password});
console.log("reached means it is synchronous");
response.status(200).json({'successmessage' : 'Successfully Signed Up'});
} catch (e) {
response.status(400).json({'errormessage': e.message});
}
我想在位置1和2的file1.js中抛出错误,我想在file2.js(从中调用它)中捕获它,然后处理它。
有人可以帮忙怎么做? 我对nodejs很新。
我读到了这样一个事实:我们不能像回调那样在回调中抛出错误,因为它只会使代码崩溃。 我接下来也读到了这个,但我认为我没有理解它,所以不知道实际上要通过的地方。 如果有人解释它并帮助我以正确的方式解决这个问题会很好。
答案 0 :(得分:1)
如何使用promise承诺:
export default class User {
constructor() {
this.userSchema = new Schema({
username: String,
password: String,
});
this.usermodel = Mongo.getModel('user', this.userSchema);
}
signUp({username, password}) {
var me = this;
return new Promise(
function(resolve,reject) {
var user = new me.usermodel({username: username,password: password});
me.usermodel.findOne({username: username}).exec((err, userresult) => {
if (err) {
reject(err);
} else {
if(userresult) { // one user case so
reject(new Error(
"User with me Username already exists !. Please try a new Username."
));
} else { // null case
resolve(new DbResult({}));
}
}
})
}
)
}
}
const user = new User();
user.signUp({username: request.body.username, password: request.body.password})
.then(//success
function(result){
//do something with result
response.status(200).json({'successmessage' : 'Successfully Signed Up'});
}
)
.then(//fail
undefined //no success handler
,function(err){
//do something with error
response.status(400).json({'errormessage': e.message});
}
);