Eric
Eric

Reputation: 1034

Asynchronous return issue

I'm trying to write a function which i can use in an if statement for logic. I've used callback functions to avoid having undefined response due to the asynchronous nature of Javascript. Am i going about this all wrong? is there a better way?

if(emailExists(Email, someCallback)){
  //email does exist, do stuff
}

Basically i just want a function to tell me if an email exists in my database to return true, But even with all the precaution i took i'm still getting undefined when i run this code.

function someCallback(e){
  console.log(e);
  return e;
}

function emailExists(input, callback) {
  pg.connect(conString, function(err, client, done){
    //Connect to database

    client.query('select email from users', function(err, result){
      //select all emails from database

      var tempArray = [];
      for(var x = 0; x < result.rows.length; x++){
        tempArray.push(result.rows[x].email)
      } //create array of emails

      callback(tempArray.includes(input));
    });
  });
}

Upvotes: 0

Views: 47

Answers (2)

adrianj98
adrianj98

Reputation: 573

You just need to put your if statement in the callback.

emailExists(Email, function(hasMail){
    if(hasMail){
        //email does exist, do stuff
     }
 });

Promise would be good but not required.

Upvotes: 0

baao
baao

Reputation: 73211

I would recommend using a Promise instead, that makes working with async much more convenient. I didn't use pg-js before and don't know if it does support promises by itself - if so, you can simply use the promise returned by it; if not, below code will work for you:

function emailExists(input) {
    return new Promise((resolve, reject) => {
        pg.connect(conString, function (err, client, done) {
            client.query('select email from users', function (err, result) {
                var tempArray = [];
                for (var x = 0; x < result.rows.length; x ++) {
                    tempArray.push(result.rows[x].email)
                }
                resolve(tempArray.includes(email));
            });
        });
    });
}

You can then use it like this:

emailExists("[email protected]")
    .then(exists => {
        if (exists) {
            // email exists
        } else {
            // not
        }
    });

Upvotes: 3

Related Questions