0

I have read many answers on this and all they give me is mostly just explanation about asynchronous functions and how they work in JavaScript. I'm still clueless as to how to get this done.

So I have this function:

function validateInput(data) {
    var errors = {};
    var testuser = {};

    console.log('LOG 1: errors', errors);

    User.find({email: data.email }, function(err, user) {
        if (user) {
            errors.email = 'Email already exists';
            testuser = user; // This doesn't set testuser in function scope
            console.log('LOG 2: test user', testuser);
        }
    });

    console.log('LOG 3: user', testuser); // test user is null despite having set it in callback
    console.log('LOG 4: errors', errors);

    return errors;
}

When I run this function, my console.logs are in the following order:

LOG 1: errors {}
LOG 3: user {}
LOG 4: errors {}
LOG 2:  [ 
        { 
         username: 'John',
         email: 'john@test.com',
         password: 'john',
         passwordConf: 'john',
         } 
    ]

This result, (the fact that LOG 2 comes last despite appearing second in my code) now makes sense to me after reading something about asynchronous functions.

My goal is to pass the user returned from callback function in User.find() (async call) to the function-scoped variable testuser.

I would appreciate any help on this.

Awa Melvine
  • 3,797
  • 8
  • 34
  • 47

0 Answers0