L
L
last_round2018-04-01 12:51:00
JavaScript
last_round, 2018-04-01 12:51:00

What is the correct way to return a function?

The NodeJS server accepts a post request:

router.post('/register', urlencodedParser, function(req, res) {
    var regUser, resp;
    regUser = new User();
    resp = regUser.register(req.body);
    console.log(resp);
    return res.send(req.body);
});

I also have a User constructor function that has a register method
(When a post request arrives, register the user), here is the code:
User = (function() {
    function User() {}

    User.prototype.register = function(obj) {
      var codeFunc, newUser;
      codeFunc = 0;
      newUser = new userSchema({
        login: obj.login,
        password: obj.pass,
        email: obj.mail
      });
      userSchema.find({
        login: obj.login
      }, function(err, docs) {
        if (err) {
          throw err;
        }
        if (typeof docs[0] === 'object') {
          return console.log('Login already is used', codeFunc = 401);
        } else {
          return newUser.save((function(_this) {
            return function(err) {
              if (err) {
                throw err;
              } else {
                codeFunc = 201;
              }
              return console.log(codeFunc = 201);
            };
          })(this));
        }
      });
      return codeFunc;
    };

    return User;

  })();

The register method performs a database search for a user with the same name that was passed to the function, and if there is a match, then I assign codeFunc = 401 to the variable (meaning the login is busy) and so on.
Problem: the register function should return a code (401 or 201), but first it handles console.log(resp); (which I wrote at the beginning), and after it already console.log(codeFunc = 201); (which fulfills if the user is successfully registered). And it turns out that at the output of the register function I have 0 (codeFunc = 0, I declare it myself), and not the operation code.
5ac0ab4bbf182736491863.png

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vladimir Skibin, 2018-04-01
@last_round

Your search is asynchronously performed, and the last return is synchronously processed. Wrap the function in a promise or use async/await.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question