Retrieve value from nested functions javascript [duplicate] - javascript

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 7 years ago.
I have had a look, and see some great examples of nesting functions, but even with reading them, I cannot see why I am getting undefined when i call this function:
function readBttnDetec() {
var devid = localStorage.getItem('vBttn');
var bd = 0;
bd = ble.read(devid, 'fffffff0-00f7-4000-b000-000000000000',
'FFFFFFF2-00F7-4000-B000-000000000000',
function(t) {
var data = new Uint8Array(t)
console.log('returns: ' + data[0]); // this returns 6
return data[0];
}, function(f) {
console.log(f);
});
return bd;
}
This is the call:
//check button state
var detecs = readBttnDetec();
console.log(detecs);
if(detecs == 2) {
// fall detection disabled
$('#playfall').removeClass('km-state-active');
} else if(detecs == 6) {
// fall detection enabled
$('#playfall').addClass('km-state-active');
} else {
// error reading button
}
I am missing something simple I am sure of it, but I cannot see it.
Thanks in advance

Related

Unable to return value inside function in node.js [duplicate]

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 last month.
The community reviewed whether to reopen this question last month and left it closed:
Original close reason(s) were not resolved
Unable to return value inside function in node.js . Below is my function which I am calling from another function to get desired value but I am getting undefined.
const getBBBMeetingInfo = (meetingID) => {
let bbbHttp = bbb.http;
let getMeetingInfo = api.monitoring.getMeetingInfo(meetingID);
let val;
bbbHttp(getMeetingInfo).then((result) => {
let newRes = {};
newRes = result;
newRes.meetingID = meetingID;
if(newRes.returncode == 'FAILED'){
updateNotificationCallStatus(meetingID)
}
val = newRes.returncode
});
return val
}
calling fuction like this
let bn = getBBBMeetingInfo(ele.meetingId);
console.log(bn)//undefined
I am new to node.js. Please let me know how I can get it and use it as returned value.

How can I update the global variable from inside a function [duplicate]

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 1 year ago.
I have the following code
binance.prices('BNBBTC', (error, ticker) => {
priceNow = ticker.BNBBTC;
console.log(priceNow)
});
But I need to use the variable "priceNow" outside of that function, I have tried many things, for example:
var priceNow = ""
binance.prices('BNBBTC', (error, ticker) => {
priceNow = ticker.BNBBTC;
// console.log(priceNow)
});
console.log(priceNow) //But this just say nothing
But this doesn't work, I can't update the global variable from the function, why does this happen? and because if it works in example like this:
var a = 10;
myFunction();
function myFunction(){
a = 20;
}
console.log("Value of 'a' outside the function " + a); //outputs 20

need help, conditional if and problems with variables, return empty [duplicate]

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

Variable changed inside arrow function not changed when consoled outside the arrow function [duplicate]

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 am working with angular and typescript and want to change the value of the variable inside the function. I am using a service to get the data. The code is shown below:
isValue:boolean = false;
onChangeValue(list: List) {
this.someServive.getData(list).subscribe(
item => {
if(item.value === 1) {
this.isValue = true;
}
});
console.log(this.isValue); //the value is still false here
}
Good day!
It happens due to the fact, that your service call is an async operation. And browser doesn't wait when your service emits some value, which you handle in subscription block.
isValue = false;
onChangeValue(list: List) {
this.someServive.getData(list).subscribe(item => {
if (item.value === 1) {
this.isValue = true;
this.executeOnUpdateCallback();
}
});
}
executeOnUpdateCallback() {
console.log(this.isValue); // true
}
Something like this you should do to handle it. I hope, you got it (please google about js event loop)
Since javascript is asynchronous, the value won't change until the getData service call actually happens.
In your case console executes before the getData happens.
You can either try it with promise or callback
Try below:
isValue:boolean = false;
onChangeValue(list: List) {
onDataRecieved((res)=>{
console.log(this.isValue);
});
}
onDataRecieved(cb){
this.someServive.getData(list).subscribe(
item => {
if(item.value === 1) {
this.isValue = true;
cb(true);
}
});
}

Problem fetching value in Array - XMLHttpRequest [duplicate]

This question already has answers here:
JavaScript closure inside loops – simple practical example
(44 answers)
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 4 years ago.
I am trying to make multiple requests on the server within a loop for. I found some tips here and implemented the suggested solution. However, it does not seem to work.
var valuePlan = [];
function getValue(id) {
var f = (function(){
var xhr = [], i;
for(i = 0; i < id.length; i++){ //for loop
(function(i){
xhr[i] = new XMLHttpRequest();
url = "get.php?id=" + id[i] + "&for=monthly";
xhr[i].open("GET", url, true);
xhr[i].onreadystatechange = function(){
if (xhr[i].readyState === 4 && xhr[i].status === 200){
console.log('Response from request ' + i + ' [ ' + xhr[i].responseText + ']');
valuePlan.push(xhr[i].responseText.replace(".", ","));
}
};
xhr[i].send();
})(i);
}
})();
};
getValue([48,52,50]);
console.log(valuePlan[0]);
The problem that when I use console.log(valuePlan[0]); in console it returns undefined, and if it uses console.log(valuePlan); returns the arrays with the correct values. Can you understand that?
The variable is already defined as global, and even then I can not fetch the individual values of it.

Categories

Resources