tom894
tom894

Reputation: 519

Returning value within function

I have the following function:

const findUserByEmail = (email) => {
  var user
  MongoClient.connect(url, (err, db) => {
    const dbo = db.db('users')
    dbo.collection('users').findOne({email: email}, (err, result) => {
      if (err) throw err
      else return result
    })
    db.close()
  }).then((user) => {
    return user
  })
}

I am trying to return the value of user so that findUserByEmail(email)=user but can't figure out how. I have tried using async/await and promises to return this value to get around Node's asynchronous nature however in each I could not get the value to return to the main function. In this case, return user returns the user to the then() function, which is not correct.

Any help would be much appreciated.

Upvotes: 0

Views: 30

Answers (1)

Dan Starns
Dan Starns

Reputation: 3825

Your very close but there is one thing your missing with your function findUserByEmail it needs to return a Promise. With a Promise you can call resolve in the future with the result from findOne. This will also change how you consume the findUserByEmail function.

Example

const findUserByEmail = (email) => {
    return new Promise((resolve, reject) => {
        MongoClient.connect(url, (mongoError, db) => {
            if (mongoError) {
                return reject(mongoError)
            }

            const dbo = db.db('users')

            dbo.collection('users').findOne({ email: email }, (findError, user) => {
                if (findError) {
                    return reject(findError)
                }

                db.close();

                return resolve(user)
            })
        })
    })
}

To consume this function you can use Promise.then(user => ) or the preferred approach of using async/await.

Consuming using .then()

findUserByEmail("email.com").then(user => {
    // do something
}).catch(err => {
    // do something
})

Consuming using async/await

async function test() {
    try {
        const user = await findUserByEmail("email.com");
        // do something
    } catch (error) {
        // do something
    }
}

Upvotes: 2

Related Questions