0
我使用调用类下面的代码在nodejs中使用类和承诺时出错?
var user_ctx = new user();
user_ctx
.set_email(req.body.email)
.then(user_ctx.set_username(req.body.username))
.catch((err)=>{
console.log(err);
});
和类的定义如下
function user() {
this.user = {};
};
user.prototype.set_username = function (username) {
return new Promise((fullfill,reject)=>{
this.user.username = username;
fullfill();
});
};
user.prototype.set_email = function (email) {
return new Promise((fullfill,reject)=>{
var email_ctx = new email_lib(email);
email_ctx
.is_valid()
.then(function() {
this.user.email = email;
})
.then(fullfill)
.catch(reject);
});
};
的问题是,email
我们不要在用户定义的。我也尝试以下
user.prototype.set_email = function (email) {
return new Promise((fullfill,reject)=>{
var email_ctx = new email_lib(email);
var that = this;
email_ctx
.is_valid()
.then(function() {
that.user.email = email;
})
.then(fullfill)
.catch(reject);
});
};
从而使用that
回调函数内引用它;但电子邮件仍未设置。已经尝试记录变量email
是否存在承诺链set_email
我在哪里出错?
'返回新的承诺((fullfill,拒绝)=> { this.user.username =用户名; });' - 这是一个承诺这永远不会是任何事情,但一个悬而未决的承诺 - 这没有任何价值 –
@JaromandaX我忘了将'fullfill()'代码添加到该块只是为了保持代码简短和重点。问题是在'this.user'中设置电子邮件的值时,'username'的设置工作正常,我通过编写另一种方法来打印出相同的内容 – georoot
,同时你也犯了经典承诺反模式 - https://stackoverflow.com/questions/23803743/what-is-the-explicit-promise-construction-antipattern-and-how-do-i-avoid-it –