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 5 years ago.
I'm a bit tired and I can't see why I'm getting undefined errors on the variable cat.data[0].id.
var app = {
initialize: function() {
this.bindEvents();
},
bindEvents: function() {
function Trial() {
var index = 0;
var cat = [];
function getcat() {
.
.Makes a call to get JSON set of data in the form
.{"status" : "success", "data" : [{"id":"8", "url":"http:\/\/google.com", "description":"Search Engine"}]}
.
request.success(function (data) {
cat = $.parseJSON(data);
if (cat.status === "error") {
alert(cat.message);
}
console.log(cat.data[index].id);
alert(cat.data[0].id);
});
request.error(function (data, status) {
alert("Error connecting to API:" + status);
});
}
}
function tests() {
getcat();
console.log(cat.data[index].id);
}
So when we call tests function it pulls the data and puts into array and the entries for console.log and alert do exactly as they should and display the id field value. However when it returns to tests and does the console.log entry there it fails with:
"Unable to get property '0' of undefined or null reference"
It's a global variable in the master function so why isn't it able to access it?
Related
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 3 years ago.
I have to create a number of RabbitMQ channels in succession, so I am trying to parameterize their creation in a function whose return value would be the channel. The function is declared in the callback-of-a-callback to the connection function.
var otaChannel = null;
amqp.connect(amqp_url, (err0, conn) => {
if(err0) {
throw(err0);
}
function getConsumerChannel(channelname) {
conn.createChannel((err1, ch) => {
if(err1) {
throw(err1);
}
ch.assertQueue(channelname, '', (err, q) => {
console.log(' [*] Created ' + q.queue + '.');
return ch;
});
});
}
otaChannel = getConsumerChannel(otaQName);
});
If I do "console.log(ch)" in the assertQueue function, I see the details of the channel. However, otaChannel in the final line of the code is always null. I've tried a bunch of variations of the code I posted, but cannot get the channel assigned to otaChannel. Where am I going wrong?
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 5 years ago.
I have the following function but I can't seem to get returnedData = result to successfully set the value. If I include alert(result) in the same location, the popup displays the string I'm looking for correctly.
Is there something I'm missing here? I had thought because I declared the variable returnedData outside the function it would be accessible everywhere?
function AJAXprocesstwoVariables(Var1, Var2) {
var V1 = Var1,
V2 = Var2;
var returnedData;
$.post(
processinglocation, {
data1: V1,
data2: V2
},
function (result) {
returnedData = result; // *<- this doesn't work*
// alert(result); // *<-this works*
}
);
return returnedData;
}
var ReturnedInfo = AJAXprocesstwoVariables(Var1, Var2);
$('body').append(ReturnedInfo);
$.post will run asynchronously. Once that line is run, the request will be made in the background, and you will immediately hit the return line of AJAXprocesstwoVariables. You are attempting to use returnedData before it is set in the success function of your $.post.
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.
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 6 years ago.
This is my code:
document.getElementById('revealUser').onclick = displayDaUsers
function displayDaUsers(){
pullAllUsersFromDB();
debugger;
}
function pullAllUsersFromDB(){
rootRef.child('users').on('value', function(snapshot) {
var users_array = [];
var users_object = snapshot.val();
Object.keys(users_object).map(function(key) {
users_array.push(users_object[key]);
});
// window.dateApp.allUsers = users_array;
return users_array
});
}
html:
<input type="submit" id="revealUser" value="reveal user">
I put a debugger in to see the problem but it does not help. When I go into the console and type in users_array
I get Uncaught ReferenceError: users_array is not defined(…)
NEW CODE (EDIT):
according to another stackoverflow answers this should work..
function displayDaUsers(){
var test = pullAllUsersFromDB();
console.log(test);
//pullAllUsersFromDB();
//debugger;
//setUpFirstUser()
}
function pullAllUsersFromDB(){
rootRef.child('users').on('value', function(snapshot) {
var users_array = [];
var users_object = snapshot.val();
Object.keys(users_object).map(function(key) {
users_array.push(users_object[key]);
});
//window.dateApp.allUsers = users_array;
return users_array
});
}
The return value users_array is local to the scope of the anonymous callback function function(snapshot) {.... In other words, its value is lost outside of that scope.
At what point in your logic do you need access to user_array? If you need access to it outside of the context of your functions, maybe it makes sense to define a variable with greater scope, and then setting its value in your anonymous function. E.g.
document.getElementById...
var arr;
...
function pullAllUsersFromDB() {
...
...function(snapshot) {
arr = users_array;
});
}
// pullAllUsersFromDB() (and its callback) must be called for arr to be defined at this point in execution
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 8 years ago.
I have a global object declared at first line. Then filling the data into it using jquery getJSON. The issue here is I am getting empty object inside function slider, whereas inside getJSON it is printing proper data. Any idea whats wrong here?
var allslides = {};
$.getJSON("data/slides.json", function(data) {
$.each(data, function(key, val) {
allslides[key] = { image : val.image, title: val.title, desc:val.desc };
});
console.log(allslides); // First
});
$(function(){
slider();
});
function slider() {
console.log(allslides); // second
}
Move your call to slider into your .getJSON as it is asynchronous:
$.getJSON("data/slides.json", function(data) {
$.each(data, function(key, val) {
allslides[key] = { image : val.image, title: val.title, desc:val.desc };
});
slider();
});