Answer the question
In order to leave comments, you need to log in
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
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
, res
the third parameter , a callback
function that you can call inside callback
the -function passed findOne
and 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 callback
is, google it, these are the basics. async function getUser (req, res) {
//...
const result = await new Promise(resolve => users.findOne(cookies, (err, result) => {
if (err) { console.log("err: " ,err) }
resolve(result);
}))
await
: or as .
If you don't know what it is or \ - google, these are the basics. const result = await getUser(req, res)
Promise
Promise
async
await
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question