2017-08-19 30 views
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我在哪里出错?

+2

'返回新的承诺((fullfill,拒绝)=> { this.user.username =用户名; });' - 这是一个承诺这永远不会是任何事情,但一个悬而未决的承诺 - 这没有任何价值 –

+0

@JaromandaX我忘了将'fullfill()'代码添加到该块只是为了保持代码简短和重点。问题是在'this.user'中设置电子邮件的值时,'username'的设置工作正常,我通过编写另一种方法来打印出相同的内容 – georoot

+0

,同时你也犯了经典承诺反模式 - https://stackoverflow.com/questions/23803743/what-is-the-explicit-promise-construction-antipattern-and-how-do-i-avoid-it –

回答

1

按照预期的代码不能正常工作,由于一些错误/不正确执行:

  1. 您立即拨打user_ctx.set_username,无需等待的承诺将得到解决。而不是.then(user_ctx.set_username(req.body.username))您必须使用:.then(() => user_ctx.set_username(req.body.username))
  2. 您通过构造函数创建Promise,当调用服务email_ctx已经返回承诺。
  3. 您使用错误的this。函数内部this指向父函数。

正确实施可能是这样的:

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_email = function(email) { 
    var self = this; 
    var email_ctx = new email_lib(email); 
    return email_ctx 
     .is_valid() 
     .then(function() { 
      self.user.email = email; 
     }); 
    }); 
}; 

user.prototype.set_username = function (username) { 
    this.user.username = username; 
};