Problem fetching value in Array - XMLHttpRequest [duplicate] - javascript

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.

Related

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

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

Asynchronous (setTimeout) lambda doesn't use correct inputs [duplicate]

This question already has answers here:
JavaScript closure inside loops – simple practical example
(44 answers)
Javascript setTimeout, Loops and Closure
(1 answer)
Closed 9 years ago.
I got the below code within a callback of xmlHTTPRequest callback function:
// some more code before
...
// schedule the UI update
var totSteps = 6;
for(var i = 0; i < listChangeEl.length; ++i) {
// callback pulse function
var curPulse = function cell_pulse(elName, curCnt) {
console.log("Accessing element: " + elName);
var curEl = document.getElementById(elName);
console.log("Element: " + elName + " = " + curEl);
var curColor = RGB2HTML(255, 255*(curCnt/totSteps), 255*(curCnt/totSteps));
if(curCnt < totSteps) {
// recursion here!
setTimeout( function(){ cell_pulse(elName, curCnt+1); }, 125);
}
};
// start it!
setTimeout( function() { (curPulse)(listChangeEl[i], 0); }, 125);
}
Apparently when the above is setTimeout( function() { (curPulse)(listChangeEl[i], 0); }, 125); is executed , listChangeEl[i] does contain the right id of a cell I want to update, but then, upon first execution of function cell_pulse the parameter elName is undefined.
What am I doing wrong? Does Javascript manage lambda (of lamdba) properly?
Thanks,
Ema

Categories

Resources