Home > Net >  NODE.JS: How can I return value from this nested function?
NODE.JS: How can I return value from this nested function?

Time:03-12

function authenticateUser(un, pwd){
  users.find({username: un}).toArray((err, items) => {
    try{
      bcrypt.compare(pwd, items[0].password, function(err, result) {
      // i want to return this result
    });}catch (error){
      console.log("")
      // in this case i want to return false
    }
  })
}

How can I return data from this nested function?

CodePudding user response:

You cannot use data from async function out of it's own scope. You can read this answer on SO to better understand how async calls work.

You can update your code to make it work.

function authenticateUser(un, pwd, callback) {
    users.find({
        username: un
    }).toArray((err, items) => {
        bcrypt.compare(pwd, items[0].password, (err, isMatch) => {
            if (err) {
                console.log(err)
            }
            callback(null, isMatch);
        })
    })
}

Then when you want to use this function you can use it like this

authenticateUser(user, enteredPassword, (err, isMatch) => {
            if (err) {
                console.log(err)
            }
            if (isMatch) {
                console.log(`YAY Password Matched`);
            }

CodePudding user response:

You can use promises to do this.

function authenticateUser(un, pwd){
  return new Promise((resolve, reject) => {
      users.find({username: un}).toArray((err, items) => {
      if (err) reject(err);

       bcrypt.compare(pwd, items[0].password, function(err, result) {
       if (err) reject(err);
       resolve(result);
       // i want to return this result
     })
    })
 })
}


async function main() {
   try {
     const result = await authenticateUser(un, pwd);
     console.log(result);
  } catch(e) {
     console.error(e);
  }
} 

How to work with async/await check here.

Note: try/catch doesn't work with callbacks.

  • Related