N
N
NZ012021-10-16 08:22:33
MongoDB
NZ01, 2021-10-16 08:22:33

How to find the user first and then return it?

Hello. I'll try super briefly, I tested my code and realized that first the function that finds the user using cookies AND THEN returns him, does the opposite, and I need to return a variable with the user only if he was found:

function getUser (req, res) {
        const cookies = req.cookies["account"]

        if(!cookies) {
            console.log("cookies is not defined", cookies)
        }
        else {
            const result = users.findOne(cookies, (err) => {
                if (err) { console.log("err: " ,err) }
            })

            if(result) {
                console.log("result: ", result)
                return result
            }
            else {console.log("result is not defined: ", result)}
        }
    }

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Aetae, 2021-10-16
@Aetae

Synchronized - no way.
The return from a normal function occurs immediately, without options. If something inside her takes an unknown amount of time, she won't wait for it. (because js is initially single-threaded, and if the function waited for something synchronously, the page would completely freeze for the entire waiting time)
You can pass after req, resthe third parameter , a callbackfunction that you can call inside callbackthe -function passed findOneand pass the result to it.

function getUser (req, res, callback) {
// ...
users.findOne(cookies, (err, result) => {
  if (err) { console.log("err: " ,err) }
  else if(result) {
    console.log("result: ", result)
    callback(result);
  }
  else {console.log("result is not defined: ", result)}
})
If you don't know what it callbackis, google it, these are the basics.
You can change the function to be asynchronous:
async function getUser (req, res) {
//...
const result = await new Promise(resolve => users.findOne(cookies, (err, result) => {
  if (err) { console.log("err: " ,err) }
  resolve(result);
}))

It will only be possible to call such a function only in another asynchronous function via await: or as . If you don't know what it is or \ - google, these are the basics.
const result = await getUser(req, res)Promise
Promiseasyncawait

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question