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.
Related
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
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);
}
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
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 8 years ago.
I'm trying to assign a function's return value to a variable, using this stackOverflow article as a template. Here's my code:
var host = getHostName(djId, function(name) {
return name;
});
console.log(host); // undefined :(
function getHostName(id, cb) {
var reply;
userColl.findById(id, function (err, dj) {
if (err) {
reply = "db error";
} else {
reply = dj.firstName + ' ' + dj.lastName;
}
console.log(reply + ' reply'); // working as expected!
cb(reply);
});
}
the console.log(reply) is working as expected but host is still undefined when i try t call the function. what gives?
Because it's the result of getHostName which itself doesn't return anything. It seems like an asynchronous function, so if you need to do something with the value, you have to put it inside of the callback.
The inner function (callback) is executed asynchronously so when it runs, the execution of getHostName is already finished. And that's why the inner function can't return anything to the variable. All code, which will do something with the name, has to be inside of the callback.
var host = getHostName(djId, function(name) {
console.log(name); // Here you go
anotherFn(name); // Here you can have the rest of your code which needs the name
});
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
How to return AJAX response Text? [duplicate]
(2 answers)
Closed 9 years ago.
This question is already answered and voted. My edits are related to making it clearer and share some new knowledge acquired for other developers, I'm not expecting new answers.
I'm reading an XML with jQuery, but when I try to show an alert it's fully working; however, when I try to return the value it always gives me a message that it's undefined.
function getText(value){
var val;
var lang;
var location;
lang=getLanguage();
if (lang=='en')
lang='';
else
lang+='.';
location="resources/AppResources."+lang+'xml';
$.get(location, function (xml) {
$(xml).find("data").each(function () {
var name=$(this).attr('name');
if (name===value)
return $(this).find('value').text();
});
});
}
This is the code that calls it:
$(document).ready(function() {
alert(getText('AppTitle'));
});
If I add an alert in the return statement it shows me the value selected.
Small update:
As Arun P Johny explained in his answer, the missed part in my code was the callback that are defined by Mozilla in this way:
A callback function is a function passed into another function as an argument, which is then invoked inside the outer function to complete some kind of routine or action.
You can't return a value from a async method, the easiest solution is to use a callback function like this one:
function getText(value, callback) {
var val;
var lang;
var location;
lang = getLanguage();
if (lang == 'en')
lang = '';
else
lang += '.';
location = "resources/AppResources." + lang + 'xml';
$.get(location, function (xml) {
$(xml).find('data[name="' + value + '"]').each(function () {
callback($(this).find('value').text());
});
});
}
$(document).ready(function() {
getText('AppTitle', function(value){
alert(value);
})
});