MongoDB .findOne scope [duplicate] - javascript

This question already has answers here:
Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference
(7 answers)
Closed 6 years ago.
I have a problem with var scope.
var max;
ClassModel.findOne({ class: '1a' }, function (err, class1a) {
if (err) return handleError(err);
max = class1a.members;
console.log(max);
});
console.log(max);
Why first log logs proper value, but second logs undefined?

Second console.log shows undefined because findOne of mongoose is asynchronous. When you show the first console.log, the result has been processed, in the second not.
Mongoose async operations, like .save() and queries, return
Promises/A+ conformant promises. This means that you can do things
like MyModel.findOne({}).then() and yield MyModel.findOne({}).exec()
(if you're using co).
One thing as you can do is to check when it is done, something like..
var max;
var query = ClassModel.findOne({ class: '1a' }, function (err, class1a) {
if (err) return handleError(err);
return class1a.members;
});
query.then(function(data) {
console.log(data); // will show class1a.members value
});
Docs

Related

Why does await is not working in my function? [duplicate]

This question already has answers here:
How to return many Promises and wait for them all before doing other stuff
(6 answers)
Closed 2 years ago.
I am trying to push in an array all the ids of objects that match my condition.
I am using a recursive function and I want to return a value when my recursive function has finished.
Here is my code :
const getFamilies = async function (family, famillesReliees) {
await strapi.query('famille-de-materiel').findOne({ id: family })
.then(res => {
if (res.cats_enfant.length > 0) {
res.cats_enfant.forEach(async enfant => {
famillesReliees = await getFamilies(enfant.id, famillesReliees)
})
} else {
famillesReliees.push(res.id)
}
})
return famillesReliees
}
async search() {
let value = await getFamilies(2, [])
return value
}
I don't understand why the "value" return before the end of the recursive function
This isn't doing what you think:
getFamilies(2).then(console.log('getFamilies then'))
This executes console.log immediately and passes its result (which is undefined) as the function to be executed after the getFamilies operation.
Wrap the console.log operation in a function to be executed later:
getFamilies(2).then(() => console.log('getFamilies then'))
Structurally, this is just like your use of .then() in the getFamilies function above. The only differences are:
There are no parameters/arguments for the function, so just use () instead of a variable name. (Your callback function above has a parameter called res.)
There's only one line in the function, so the curly braces {} aren't needed. (Technically this also returns the result of that line, but in this case the returned result is undefined and nothing uses it so no harm done.)

Async Function and Promise [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference
(7 answers)
Closed 2 years ago.
I am a newbie in JavaScript, trying to implement code to connect to MySQL. I am using Promise along with Async/Await function. My goal is to get the return value of the Promise object.
However, I have read and tried every possible way but still failed to understand how the Asynchronous function works in JavaScript as the return value of the function getData() still return an object
Promise { < pending > }
I also tried to use then but it still returns the same result. I would really appreciate it if someone can show me what I have misunderstood or where I did wrong in this function. Thank you!
Here is my JS code:
function test_connection() {
var connection = #MySQLConnectionObject;
return new Promise((resolve, reject) => {
connection.connect((error, result) => {
if (error) {
reject(error)
} else {
connection.end();
resolve("Successfully Connected!");
}
});
});
}
async function getData() {
var result = await test_connection()
return result;
}
var result = getData();
console.log(result);

Sync function wraps Async operations [duplicate]

This question already has answers here:
How to return value from an asynchronous callback function? [duplicate]
(3 answers)
Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference
(7 answers)
Closed 5 years ago.
Say we have the following if statement
.
.
if (!user.comparePassword(password)) {
return done(null, false, { message: 'Incorrect password.' });
}
.
.
where comparePassword(password) is a function to check if the user input password is identical to the one in the database.., and it's in another module being defined as follows:
userSchema.methods.comparePassword = function (password) {
let match = false;
bcrypt.compare(password, this.password)
.then(function (isMatch) {
if(isMatch){
match = true;
}
})
.catch(function (err) {
// handle error
});
return match;
};
The problem is in I/O.., where one could easily see the if statement depends on a function comparePassword(password) that could finish execution before the promises inside it bcrypt.compare() finishes execution.., which means I get match most of the time false even if it should technically be true. the compare function of bcrypt runs an expensive operation, so how do I get the result of comparison in time without blocking code-execution ?

access variable after define it inside a function [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 6 years ago.
I'm trying to access a variable outside a function, but I'm getting undefined
meliObject.get('users/me', function (err, res) {
nickname = res.nickname;
});
console.log(nickname);
How can I access nickname?
EDIT
I changed my code for:
var nickname;
meliObject.get('users/me', function (err, res) {
nickname = res.nickname;
});
console.log(nickname);
But I'm still getting undefined
The result of that function is asynchronous, so you cannot do this. Javascript flow goes like this: run meliObject.get, return immediately, run console.log(nickname), and then wait for the callback to be called. To console.log properly, just do this:
meliObject.get('users/me', function (err, res) {
nickname = res.nickname;
console.log(nickname);
});
Now, to answer your question, to declare a variable outside a function, just use var/let/const:
var a = 2;
(function () {
a = 3;
})();
console.log(a);
It will print as expected.

How to return value from Node.js function which contains DB query [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 6 years ago.
I'm learning Node.js and I'm just starting to work with some MySQL connections. I have a function which is supposed to get a set of rows from the database, which it does correctly. However, I don't know how to return that set of rows afterwards. I tried two options (both explained in comments within the code segment below.
function fetchGameList(){
var ret = 0;
connection.query("SELECT * from tbl", function(err, rows, fields) {
//some stuff happens here, and 'ret' is set to a vlue, for instance
//ret = 7;
//ret has the value 7 here, but if I put 'return ret' here, nothing is returned
});
return ret; //returns 0 because Node is asynchronous and the query hasn't finished yet
}
So, the question is, how do I return the correct value of ret (7 in this case)? Am I even structuring this properly?
You need to pass a callback into your function. Convention is that the callback takes an error (or null if none happened) as the first argument, and results as other arguments.
function fetchGameList(callback) {
var ret;
connection.query("SELECT * from tbl", function(err, rows, fields) {
if (err) {
// You must `return` in this branch to avoid using callback twice.
return callback(err);
}
// Do something with `rows` and `fields` and assign a value to ret.
callback(null, ret);
});
}
You can now do something along the lines of:
function handleResult(err, result) {
if (err) {
// Just an example. You may want to do something with the error.
console.error(err.stack || err.message);
// You should return in this branch, since there is no result to use
// later and that could cause an exception.
return;
}
// All your logic with the result.
}
fetchGameList(handleResult);

Categories

Resources