Array Is Empty When It Isn't... JavaScript [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)
Closed 5 years ago.
So what I'm doing is getting values from a json file and pushing them to an array so that I can randomly select one and it is displayed in an html file. The problem i'm having is that even though something is in the array, it treats it as if it is empty...
var quotes = [];
var authors = [];
function loadJSON(callback) {
var xobj = new XMLHttpRequest();
xobj.overrideMimeType("application/json");
xobj.open('GET', 'quotes.json', true);
xobj.onreadystatechange = function () {
if (xobj.readyState == 4 && xobj.status == "200") {
// Required use of an anonymous callback as .open will NOT return a value but simply returns undefined in asynchronous mode
callback(xobj.responseText);
}
};
xobj.send(null);
}
function init() {
loadJSON(function(response) {
// Parse JSON string into object
var data = JSON.parse(response);
for(var i in data){
var key = i;
var val = data[i];
quotes.push(key);
authors.push(val);
}
});
}
init();
var index = Math.floor(Math.random()* (quotes.length + 1));
document.getElementById("p1").innerHTML = "<span class=\"quotes\">“</span>" + quotes[index] + "<span class=\"quotes\">”</span>" + "<span id=\"author\">" + " – " + authors[index] + "</span";
So in my init function it pushes the key and the val to an array but it treats it like it's empty... i'm sorry if this is a simple question but i'm pretty new at JSON. Thanks

I think your problem is that you're executing the last 2 lines of your code (those following the call to init function) before the work within the init actually completes.
In other words, pass a callback to init just like you did to loadJSON, then execute last 2 lines within.

As pointed by Xufox you are dealing with async code, when getElementById runs your request for data has not finished yet, so you end up with an empty array for innerHTML.
This is not related to your question, but void to use for ... in as much as you can when dealing with arrays, prefer old school for for that or, if you are using Babel, for of.

Related

Cant make a variable be seen outside of a function in Node js? [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 2 years ago.
I need to make the index_to_write variable to be seen outside of the function. How can I make this possible?
const XlsxPopulate = require('xlsx-populate');
let found = false;
let i = 1;
let index_to_write = 0;
XlsxPopulate.fromFileAsync("todo-list.xlsx")
.then(workBook => {
while (i <= 10 && found === false){
const value = workBook.sheet("Do-Shopping").cell("A" + i.toString()).value();
if (value === undefined) {
found = true;
index_to_write = i.toString();
}
i++;
}
});
console.log("A " + index_to_write + " is the first one to be free of data");
I tried to add return index_to_write; below the index_to_write = i.toString(); but it does not resolve the problem.
Currently, it shows 0, as in the initialization, but it should print 4. How to repair it?
Thank you very much in advanced!
Since you declare the variable outside of the function you can see it. If that was not the case, you would get undefined and not 0 as a result.
However XlsxPopulate.fromFileAsync is an async function and returns a promise, and that will not neccesarily be run imediately when the method is invoked. Therefore your console line will run before the promise is resolved.
So the execution sequence would be:
1. let index_to_write = 0;
2. XlsxPopulate.fromFileAsync("todo-list.xlsx")
3. console.log("A " + index_to_write + " is the first one to be free of data");
4. then(workBook => { ...

Pass reference variable outside the function [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
What is the scope of variables in JavaScript?
(27 answers)
Closed 3 years ago.
In a function to obtain certain data with a json, I want to use this data in a variable and then use it in another function. The problem is that it does not work for me
First of all, obtaining the data with a json and printing it in place on the screen, until now, the problem starts when I save the data in a variable
function cargarPropuestas() {
var peticionLoc = new XMLHttpRequest();
peticionLoc.open('GET', 'https://api.ipdata.co/es?api-key=b3ae31a7a74386088875d7d285250b58778e13de985b2f561910b6bd');
peticionLoc.onload = function () {
var datosLoc = JSON.parse(peticionLoc.responseText);
var elementoLoc = document.createElement('div');
elementoLoc.innerHTML += (datosLoc.city + ', ' + datosLoc.country_name);
loc.appendChild(elementoLoc);
var country = datosLoc.country_name;
}
peticionLoc.send();
What interests me here is the variable COUNTRY
And here the problem begins, since when I "leave" the requestLoc.onload = function () {} I can not call the variable COUNTRY to use it below
What I need is to know how to get the information of this variable out of the function, in order to use that data
You can declare country outside both functions.
var country;
function cargarPropuestas() {
//...
peticionLoc.onload = function () {
//...
country = datosLoc.country_name;
}
peticionLoc.send();
}

How I can return a string from a javascript callback [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 6 years ago.
How I can return a string from a javascript callback
I have two functions, main function is working on loaded.
and another function is used to calling web service.
I would like to know how can JS return the string value to main function.
thanks
function thisCallJSON(webServiceURL) {
var params = {};
params[gadgets.io.RequestParameters.CONTENT_TYPE] = gadgets.io.ContentType.JSON;
params[gadgets.io.RequestParameters.METHOD] = gadgets.io.MethodType.GET;
gadgets.io.makeRequest(webServiceURL, function(response)
{
if(response.data && response.text)
{
var jsondata = response.data;
for (var key in jsondata)
{
var value = jsondata[key];
//alert("Member Name : "+value["memNm"]);
}
}
else
{
//alert("Member Name : Not Found !");
}
}, params);
}; function main(){
var txt_string = "";
txt_string = thisCallJSON("http://192.100.1.59");
}
You can assign the value to the variable in the scope of the main function, but it won't happen before the main function is finished executing because of the event loop. Instead, you should put your code inside the callback, or better yet, look at how you would use javascript promises to accomplish this.

Get original variable value [duplicate]

This question already has answers here:
JavaScript closure inside loops – simple practical example
(44 answers)
Closed 6 years ago.
I'm trying to use a variable value in a callback function, but am unable to get the original value of the variable when written into the function.
for (i=0; i<2; i++) {
if ($.type(picker[i]) == "object") {
var id = picker[i].$root[0].id;
picker[i].on({
set: function() {
alert("#" + id + " .picker__holder");
},
});
// other code..
}
}
This code is supposed to go throught the picker object twice, where the id value is first "datepicker" and on the second run "datepicker--2" but when the callback is called the id is always the second value "datepicker--2" where for the picker[0].on() callback i'd need it to be the first one ("datepicker").
I assume this is because the value of the variable is read when the callback code is executed, and by that time it has the last value.
What would be a reasonable workaround for this?
Best,
Alari
You need to refactor the inner asynch call into a function.
for (i=0; i<2; i++) {
if ($.type(picker[i]) == "object") {
var id = picker[i].$root[0].id;
// other code..
asynhCall(picker, i, id);
}
}
function asynhCall(picker, i, id)
{
picker[i].on({
set: function() {
alert("#" + id + " .picker__holder");
},
});
}
This is because by the time asynch-callback handler was executed, only id will have only the last value would be used (since because of event-loop model).

global variable value is lost when exiting function that defines it [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 8 years ago.
I've written a piece of javascript/jquery that reads a textfile.
I'm having trouble with the variable "fieldname". I declared it in the outer function(), and I assign a value to it in the inner function() that actually reads the file. But right after I leave the inner function, the content of the variable is lost. The code:
<script>
$(document).ready(function(){
var usedlanguage = $("#usedlanguage").html();
var fieldname = new Array();
$.get('Language.txt', function(data)
{
var lines = data.split('\n');
var res="";
for(var i = 0; i<lines.length;i++)
{
var splitup = lines[i].split('\t');
fieldname[i] = splitup[0];
res = res + fieldname[i] + '\n';
}
alert("fieldname length = " + fieldname.length); // here everything is OK
alert("" + res); //this is good.
});
alert("fieldname length = " + fieldname.length); // here it suddenly returns 0.
});
</script>
Is there something wrong with my understanding of scopes? Or is it a problem that there are two function() defined? Or something else?
You need to declare the variable outside DOM ready event to make it global. currently its context remains only in ready event and not beyond that. Use it in this way::
var fieldname = new Array();
$(document).ready(function(){
//rest code
});

Categories