georoot georoot - 1 month ago 9
Node.js Question

Error while using classes and promise in nodejs?

I am calling class using following code

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);
});


and the class is defined as follows

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);
});
};


the problem is that the
email
us not defined in user. i also tried the following

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);
});
};


thereby referencing it using
that
inside callback function; but the email is still not being set. Already tried logging that the variable
email
is there in promise chain of
set_email
where am i going wrong with this ?

Answer Source

Your code doesn't work as expected, due to several errors / incorrect implementation:

  1. You call user_ctx.set_username immediately, without waiting the promise will be resolved. Instead of .then(user_ctx.set_username(req.body.username)) you must use: .then(() => user_ctx.set_username(req.body.username)).
  2. You create Promise via constructor, when calling service email_ctx is already returns a promise.
  3. You use wrong this. Inside the function this points to the parent function.

Correct implementation might look like 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;
};