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).
Related
This question already has answers here:
Why do functions return `undefined` instead of `null` by default?
(7 answers)
All falsey values in JavaScript
(4 answers)
Closed 9 months ago.
Let's say I have a function like this:
checkerFunction() {
let checker = false;
// Note here I only do a return if the *if* condition is fulfilled
if (condition) {
checker = true;
return checker;
}
}
And then I use it as a true/false check on another function:
anotherFunction() {
// What will happen here if there's no return from this.checkerFunction()
if (this.checkerFunction()) {
somethingHappens;
}
}
What will happen in
if (this.checkerFunction())
if there's no return in checkerFunction() because the condition was never true... Is it going to be interpreted as true/false or is this going to be an error and why?
Functions which end without hitting a return statement will return undefined (or a promise that resolves to undefined if they are async).
undefined is a falsy value.
This is trivial to test:
function foo () {
// Do nothing
};
const result = foo();
if (result) {
console.log("A true value: ", result);
} else {
console.log("A false value: ", result);
}
This question already has answers here:
How to return value from an asynchronous callback function? [duplicate]
(3 answers)
How do I return the response from an asynchronous call?
(41 answers)
Closed 3 years ago.
can anyone tell my why this happens?
checkSessionToken() {
var sessionToken = loginCookies.get("sessionToken");
if (typeof sessionToken !== "undefined") {
var callback = "a";
axios
.get(backendServerURL + "/login.php", {
params: {
action: "checkSessionToken",
token: sessionToken
}
})
.then(res => {
callback = "b";
console.log("---");
});
return callback;
} else {
return false;
}
}
render() {
console.log(this.checkSessionToken());
}
the function is always returning "a" ... but I see the "---" in the console so it should be "b" does anyone of you know why this happens .... sorry for might beeing a noob I'm new to js
EDIT: when I say
return "b";
in the
.then(res => {});
so it would be
.then(res => {
return "b";
});
it returns undefined
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 4 years ago.
Sorry if this question has been solved before, I have checked this, this one, too (which, I thought, was a good lead, but I failed to understand the accepted answer) and lastly this one.
I have this case in a switch statement:
function setFieldTransformation(iteration) {
//Omitting first hundred lines and switch declaration...
case "customer.subscriptionSet":
var subscriptionCode;
if (iteration.oldValue && iteration.newValue) {
if (Array.isArray(iteration.oldValue) && Array.isArray(iteration.newValue)) {
subscriptionCode = iteration.oldValue[0].service;
} else {
subscriptionCode = iteration.oldValue.service;
}
} else if (iteration.oldValue) {
if (Array.isArray(iteration.oldValue)) {
subscriptionCode = iteration.oldValue[0].service;
} else {
subscriptionCode = iteration.oldValue.service;
}
} else {
if (Array.isArray(iteration.newValue)) {
subscriptionCode = iteration.newValue[0].service;
} else {
subscriptionCode = iteration.newValue.service;
}
}
return getSubscriptionName(subscriptionCode);
break;
}
What I'm trying to achieve:
Here I check for a subscription code, then I call this function:
function getSubscriptionName(subscriptionCode) {
ServiceService.getService(subscriptionCode)
.then(function(response){
var subscriptionName = response.data.name
return response.data.name;
})
}
Which calls a service to get the subscription name. That string is then passed through this function and printed in a table:
function transformDetailValuesReworked(iteration) {
//...
var fieldSetTransformation = setFieldTransformation(iteration);
return fieldSetTransformation;
}
What actually happens:
If I understand correctly the asynchronous nature of the promises, var subscriptionName = response.data.name could never happen, so the return is undefined.
What I have tried:
I have tried a chained promise approach, but it does not behave the way I expect. Also, and even though it is not a good practice, I've tried to set up callbacks in the functions, but ultimately ending up in the same dead spot.
I'm pretty sure I can use an async function approach, but I'm concerned about compatibility issues.
Could you shed some light? Thank you.
You've simply forgotten to return anything from getSubscriptionName
function getSubscriptionName(subscriptionCode) {
return ServiceService.getService(subscriptionCode)
.then(function(response){
var subscriptionName = response.data.name
return response.data.name;
})
}
But then your next method needs to treat it as async too
function transformDetailValuesReworked(iteration) {
//...
var fieldSetTransformation = setFieldTransformation(iteration);
return fieldSetTransformation; // This is a promise not a value!
}
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
How to use $http promise response outside success handler
(3 answers)
Closed 5 years ago.
I have a $watchCollection in angularJS that calls the function getBalance(addr) in the listener.
$scope.$watchCollection('settings',
function() {
for (i = 0; i < $scope.settings['accounts'].length; i++) {
var bal = $scope.getBalance($scope.settings['accounts'][i]);
console.log(bal);
}
}
);
The function getBalance is defined as follows:
$scope.getBalance = function(addr) {
var balance;
if ($scope.settings.contract !== null) {
$scope.settings.contract.deployed().then(function(deployed) {
return deployed.balanceOf(addr);
}).then(function(res) {
balance = res.toNumber();
console.log(balance);
return balance;
}).catch(function(err) {
console.log(err.message);
});
}
return balance;
};
The problem is that in then, the balance variable is printed correctly however, in $watchCollection, return is undefined.
The problem should be because JS keeps executing without waiting for a result therefore the variable is read as undefined however, how do I have to change these two snippets of code in order to get the result when ready and append it to $scope.balance.
It looks like you're trying to change async code to sync code, which you can't really do. You need to carry the promise all the way through, in both.
Instead of setting balance to a variable and returning that variable, return the promise itself, then use then in your $watchCollection to get the value.
$scope.$watchCollection('settings',
function() {
for (i = 0; i < $scope.settings['accounts'].length; i++) {
$scope.getBalance($scope.settings['accounts'][i])
.then(bal => console.log(bal));
}
}
);
$scope.getBalance = function(addr) {
if ($scope.settings.contract !== null) {
return $scope.settings.contract.deployed().then(function(deployed) {
return deployed.balanceOf(addr);
}).then(function(res) {
balance = res.toNumber();
console.log(balance);
return balance;
}).catch(function(err) {
console.log(err.message);
});
}
return Promise.resolve(null);
};
Note, in functions that return Promises, make sure all pathways return a Promise or bad things will happen (hence the Promise.resolve(null)).
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.