0

in socket.io i am trying to check if a user exist easily enough to where i can just call

if(checkUserExist(uid) == 'true'){
    success();
}else{
    failure();
};

so i figured out i need to use promises because the function i use to get info from the database is async so i do this

function checkUserExist(uid){

    return new Promise(resolve => {
      webUser.findOne({ _id: uid }, function(err, uid) {
        if(uid){
        console.log("USER EXISTS")
        resolve('true')

        }if(!uid){
          console.log("USER NO REAL")
          resolve('false')
        }
      })
});

and when i'm trying to use the function like this

socket.on('getAgents',function(uid){
  console.log(checkUserExist(uid))
  if(checkUserExist(uid) == 'true'){
    console.log('user does exist getting agents')
    agentList.find({}, function(err, docs) {  
      docs.forEach(function(d) {
          socket.emit('newAgent', d.agentName)
       });
    });
  }else if(checkUserExist(uid) == 'false'){
    console.log('invalid uid ' + uid)
    socket.emit('serverError', 'Invalid UID '+ uid)
  }
})

the returned value is Promise { <pending> }

i am not sure what to do i thought that it was a simple enough task but obviously i don't yet know how to do it. is there anybody out there that can help me out.

promises is a fairly new concept to me and i still don't fully understand how they work should maybe use a library like promisify?

Thanks a ton :)

jfriend00
  • 683,504
  • 96
  • 985
  • 979
Nik Hendricks
  • 244
  • 2
  • 6
  • 29
  • 1
    Well for starters you shouldn't be calling it multiple times. It should be `if`...`else`, and it should be `checkUserExist(uid).then(exists => { if (exists) { ... } else { ... } })`. You should also resolve with boolean values `true` and `false`, not strings. – Patrick Roberts Nov 19 '18 at 04:42
  • Possible duplicate of [How to return value from an asynchronous callback function?](https://stackoverflow.com/questions/6847697/how-to-return-value-from-an-asynchronous-callback-function) – Patrick Roberts Nov 19 '18 at 04:42

1 Answers1

1

So, checkUserExist() returns a promise, not a value. That's how you coded it!

And, since the value is obtained asynchronously, you can't return the value directly anyway. See the canonical answer on that issue for more explanation on that topic.

To make your code work properly, you would have to actually use the promise that your function returns:

socket.on('getAgents',function(uid){
    console.log(checkUserExist(uid))
    checkUserExist(uid).then(result => {
        if (result) {
            agentList.find({}, function(err, docs) {  
                if (err) {
                    // decide what to do if there's a DB error here
                    return;
                }
                docs.forEach(function(d) {
                    socket.emit('newAgent', d.agentName)
                });
            });
        } else {
            socket.emit('serverError', 'Invalid UID ' + uid)
        }

    }).catch(err => {
        socket.emit('serverError', 'Error processing UID ' + uid);
    });
});
jfriend00
  • 683,504
  • 96
  • 985
  • 979
  • Thanks for your help once again so when you use `checkUserExist(uid).then(result =>{})` so if there is a result why does that mean that it is true because couldnt the result be false ? – Nik Hendricks Nov 19 '18 at 05:07
  • 1
    @NicholasHendricks - The resolved value in `result` could be either `true` or `false`. That's why my suggested code does `if (result) {...} else {...}` to check that and process it differently. – jfriend00 Nov 19 '18 at 05:08