2

Hello i would like to return a simple Boolean with there options: - true: user exists in database - false: user doesn't exists in database

Here's my non-working code:

database.users.get("test-username", function (err, value) {
    if (err) {
        return err;
    } else {
        return value;
    }
})

The return is always undefined I know that NodeJS is designed to work async, but async functions don't allow me to return something. I'm stuck, please help!

Also, i use LevelUP as database system. (if my problem have no solution, is there an other database system in NodeJS that allow synchronous?)

Thanks to the community!

1 Answer 1

5

Do you get anything back when you console.log your return? for example:

function dbCall(){    
database.users.get("test-username",function(err, value){
     if(err){
          return false;
     }else{
         console.log(value);
         return value;
     }
}
}

if you get something in value then the reason you don't see anything in return is because the api call is asynchronous. You'll have to make a promise.

new Promise(resolve,reject){
    let data = dbCall();
    if(data == false)
         reject(data);
    else
         resolve(data);
}
Sign up to request clarification or add additional context in comments.

3 Comments

Sure, console.log works in callback, outside the callback nothing works. I found another solution, is to call function with req and res parameters (ExpressJS), so i can display response directly with res.send(response) in callback
The reason it doesn't work is because your program does not wait for a async call to be called back before continuing. But yes req and res should work too :) However is you do need to do more complicated operations using the data, I highly recommend you look up promises and async js library.
Yes, i finally used Promise Thanks for your help!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.