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 ?
Related
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);
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.
I want to check if a file exists with nodejs from Electron. But I can't return a boolean value such as "true" or "false". The callback function doesn't return anything. Apparently the callback function executes after the main function. I tried many methods and nothing happens.
function fileExists(filename){
var result;
fs.stat(filename, function(err, stat) {
if(err === null) {
result = true;
} else if(err.code == 'ENOENT') {
result = false;
}
});
return result;
}
//usage
if(fileExists('myFile.txt') === true){
//proceed
}else{
//error
}
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
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 6 years ago.
The following Node.js code prints 'undefined', even though it found the file.
var fileFound = function() {
fs.readFile('public/images/acphotos/Friedrich-EL36N35B.jpg', function(err, data) {
if (err) {
console.log(err);
return false;
} else {
return true;
}
});
}
console.log("Return value: " + fileFound());
How would I rewrite it? I don't fully understand the solution in the other thread I was shown.
Because the return statements are inside the callback passed into fs.readFile.
the fileFound function never returns anything, therefore you get undefined.
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);