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.
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:
Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference
(7 answers)
How do I return the response from an asynchronous call?
(41 answers)
Closed 2 years ago.
I have this code in PHP and it works excellent, I am passing it to node (javascript) but it is giving me problems, it does not expect to terninate the conditionals and continues with the process, it gives me as a result the empty variable.
var variable = "";
if (typeof req.body.princp !== 'undefined') {
if (iduser == idperprincp ) {
var sqlfav = `SELECT * FROM tblfavo WHERE idusr = '${iduser }' ORDER BY id DESC`;
mysqlcon.query(sqlfav, function (err, refavsql) {
if (err) throw err;
if (refavsql.length > 0) {
variable = "restul 1"
} else {
variable = "restul 2"
}
})
} else {
variable = "restul 3"
}
} else {
variable = "restul 4"
}
console.log(variable) // Result empty..
because it always returns the bariable empty, the same code in PHP if it works well, apparently, in node (javascript) first prints the variable and then does everything within the conditional, how do you solve that problem?, thank you very much
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:
How do I return the response from an asynchronous call?
(41 answers)
Closed 6 years ago.
I currently am using data stored in Firebase to check if a user-submitted solution is correct. This involves me calling the function getSolutionAndCompare when the user presses a “submit” button. However, for some reason, although checkSolution is returning true to getSolutionAndCompare, when I call getSolutionAndCompare in onSubmitPressed, it evaluates as undefined. Any idea what I could be doing wrong?
Relevant code:
onSubmitPressed: function() {
var output = this.getSolutionAndCompare();
console.log('output ' + output); //this is returning undefined
if (this.getSolutionAndCompare()) {
Alert.alert(
'Correct',
"Woohoo!"
);
}
else {
Alert.alert(
'Incorrect Submission',
'Try again!',
);
}
},
getSolutionAndCompare: function() {
var databaseSolution;
solutionsRef.orderByChild('question_id').equalTo(Number(this.props.questionId)).once('value', (snap) => {
var solution = snap.val();
for (var key in solution) {
databaseSolution = solution[key].solution;
}
return this.checkSolution(databaseSolution); //checkSolution returns true here
});
},
checkSolution: function(databaseSolution) {
if (this.state.submission == databaseSolution) {
return true;
}
else {
return false;
}
},
getSolutionAndCompare doesn't have a return statement, so it returns undefined because that is the default.
(The anonymous arrow function you declare inside getSolutionAndCompare has a return statement, but that looks asyncronous so you can't return its value).
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 8 years ago.
I am writing a callback function in node.js but it is returning me an undefined value. Below is the code
exports.getRecord = (function(callback) {
return function(req, res) {
var recordName;
DBObject.record.find(jsonString, function(err, doc_record) {
doc_record.forEach(function(docRecordTravel) {
recordName = callback(docRecordTravel.recordCode);
console.log(recordName);
})
}
})(callbackFunc);
function callbackFunc(recordCode) {
var recordName;
DBObject.var_recordRack.find({
recordID: recordCode
}, function(err, record) {
record.forEach(function(recordLoop) {
recordName = recordLoop.recordName;
});
console.log("callback " + recordName);
return recordName
});
}
In callbackFunc it is showing me the recordName but when i return it it displays undefined. how can I return the value in call backs in node.js.
You can't.
It uses a callback function because it is asynchronous.
By the time the callback is called, the previous function has already finished and there is nowhere to return the value to.
If you want to do something with the data, then you must do it from the callback function.