How can I update the global variable from inside a function [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)
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

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.

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

Setting global array from inside readFile [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 5 years ago.
I'm probably missing something simple here, but for some reason, when I set an array's value from inside a function, I can no longer read that array once outside of that function.
var threadArray = [];
function getThreads() {
var fs = require('fs');
// read list of threads
fs.readFile('./database/threadList.txt', function(err, data) {
var threadIds = data.toString().split("\n");
for(i in threadIds) { threadArray[i] = threadIds[i].split(","); }
console.log("This works: " + threadArray[0])
})
console.log("This does not work: " + threadArray[0] + " Returns [undefined]")
}
What am I missing here? I'm assuming something to do with the way I declared the array?
This is a timing issue. fs.readFile is an asynchronous operation - your second console.log that doesn't work is getting processed immediately after fs.readFile starts running and your threadArray is not yet populated. You can use fs.readFileSync instead
try {
var threads = fs.readFileSync('./database/threadList.txt');
var threadIds = threads.toString().split('\n');
for(i in threadIds) {
threadArray[i] = threadIds[i].split(",");
}
console.log("This works: " + threadArray[0]);
} catch (e) {
console.error("Error reading file: ", e);
}

No var assignment outside scope in Javascript [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)
Closed 6 years ago.
I need to understand how come the assignment of vm.Info var does not work properly. Sorry for the bad question.
vm.getUser = function(email) {
vm.Info = ''
authentication
.avvocatoByEmail(email)
.error(function(err){
return null;
}).success(function(data){
vm.data = { user : data };
vm.Info = $crypto.encrypt(vm.data.user[0].id + "." + vm.data.user[0].email, 'myKey');
console.log("Here ok: " + vm.Info);
});
console.log("Here blank: " + vm.Info);
}
Because ajax call is asynchronous, and as a result, your second console.log (which isnt working) will get executed first; And once success event of ajax call is fired, the first console.log will work where you are assigning data to that variable.

Retrieve value from nested functions javascript [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 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

Categories

Resources