Get variable out of a multiple nested functions [duplicate] - javascript

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 9 years ago.
I'm trying to get a variable (lib) out of a multiple nested functions.
var nme='name',lib;
$('script').each(function(){
var src=$(this).attr('src');
if(typeof(src)==='undefined'){src='';}
if(src.indexOf(nme)!==-1){
$.get($(this).attr('src').match(/\w([^ ]+)spbin/)[0]+'/conf/ptmedia.plist',
function(c){
$(c).find('key').each(function(){
if($(this).html()==='MediaLib'){lib=$(this).next().html();}
});
}
);
}
});
if(lib==='some lib'){DO STUFF}

Your problem isn't with scoping, the problem is that you have an AJAX call which is asynchronous.
You should put the change of HTML in .null inside the callback function instead:
$.get($(this).attr('src').match(/\w([^ ]+)spbin/)[0]+'/conf/ptmedia.plist',
function(c){
$(c).find('key').each(function(){
if($(this).html()==='MediaLib'){lib=$(this).next().html();}
$('.null').html(lib);
});
}
});
In JavaScript often IO is asynchronous. This means that when you make an AJAX call it does not happen immidiately but rather waits for the value to return from the HTTP request and then calls a callback. In your case that function(c) is the callback, it gets executed when the value of the AJAX call arrived.
So in fact you were updating the HTML content of .null to undefined, since it got the value of lib before it was updated.

I solved this problem as follows:
var nme='name';
$('script').each(function(){
var src=$(this).attr('src');
if(typeof(src)==='undefined'){src='';}
if(src.indexOf(nme)!==-1){media=$(this).attr('src').match(/\w([^ ]+)spbin/)[0];}
});
function ffn(){
$($.ajax({url:media+'/conf/ptmedia.plist',async:false}).responseText).find('key').each(function(){
if($(this).html()==='string'){value=$(this).next().html();}
});
return value;
}
if(ffn()==='some lib'){DO STUFF}
Thank you all for your participation and good ideas!

Related

How to ensure synchronous loading in angularjs app.js [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 6 years ago.
So i have this code
getTens.getToken($rootScope.webUserInfo[0].username).then(function(resulttoken) {
$rootScope.userInfo = resulttoken;
$sessionStorage.token = resulttoken[0].token;
$sessionStorage.userInfoStorage = $rootScope.userInfo;
CasesGroupByCaseStatus.getListing($rootScope.webUserInfo[0].username).then(function(data){
$rootScope.listingDetails = data;
$sessionStorage.listingDetailsStorage = $rootScope.listingDetails;
});
CasesGroupByCaseStatus.caseStatusCount($rootScope.webUserInfo[0].username).then(function(resultcaseStatus){
$rootScope.dashboardStatus = resultcaseStatus;
$sessionStorage.dashboardStatusStorage = $rootScope.dashboardStatus;
console.log("it is finished")
});
});
return [200, { authorizationToken: $sessionStorage.token}];
In my code, i want it to complete the function first before returning the value but what happens is that it fires the return first wtout running the function, How do i handle this?
This code is my app.js. So i cant do stuffs such as scope.watch and all.
I'm not sure if this is a good way to solve the problem, but for my application I put a
$rootScope.$broadcast('loaded', true);
inside the asynchronous part's callback/success function
and then put my code inside this:
$scope.$on('loaded', function(){ //everything is loaded });
Like I said, not sure if this is a good solution or not. I used this to make my application wait for a asynchronous function to finish reading a file before starting my application. Some answer is better than no answer I guess.

Read variable inside function in Javascript? [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 7 years ago.
Right now I have three files, two javascript files and one html file that will call upon these two javascript files. Inside my first javascript file, let's call it part1.js, I have this content:
var dataval;
$.get('example.cgi', function(data){
dataval = data;
});
Inside part2.js, I am trying to call on this dataval value. But it is not working, as I am assuming that dataval is inside the get function and is therefore a local value. Is there anyway I can grab that value? My html file is calling on both of these javascripts. Is there anyway I can access that variable?
Thanks!!
There is a problem here with asynchronous calls. You should either use a callback function or make use of the jquery promise capability.
In your part1.js, you should instead define a function:
function callCgi(callback) {
$.get('example.cgi', callback); //Callback will receive the data.
}
and then use it in part2.js:
callCgi(function(data) {
//do something with data.
});
Or with promises:
function callCgi() {
return $.get('example.cgi');
}
and then use it in part2.js:
callCgi().then(function(data) {
//do something with data.
});

Scope in JavaScript / jQuery [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 clearly been writing too much CoffeeScript, as I am now realizing I do not have even a basic understanding of scope in pure JS.
After playing for a while, I cannot figure out the problem with the following--
$(document).ready(function() {
var myUrl = "http://notimportant.com/"
var photos = getPhotos(myUrl);
console.log(photos); //undefined
});
function getPhotos(url) {
var a;
$.get(url, function(data) {
a = data["photoset"]["photo"];
console.log(a); //my object
});
return a;
}
If I put a console.log(a) statement on the line right below 'var a = data["photoset"]["photo"];' it shows that it properly makes the GET request I'm looking for. But I'm finding it impossible to pass that object back to my main block of code, where I want to manipulate it.
Thanks in advance.
The reason photos is undefined is not because of scopes. Its because $.get is executed asynchronously. $.get() returns jqXHR object instead of an HTTP response.
onSuccess callback should be passed to getPhotos() in order to make it work correctly. Alternatively when().then() construct could be used.
$(document).ready(function() {
var myUrl = "http://example.com/";
getPhotos(myUrl, renderCatPhotos);
});
function getPhotos(url, onSuccess) {
$.get(url, onSuccess);
}
function renderCatPhotos(data) {
var a = data.photoset.photo;
console.log(a); // a is always available
}
note: you might not even need getPhotos function. You can simply $.get(url, onSuccess); in $(document).ready() instead.
Its not a matter of scope, its a matter of that you are returning an undefined variable before the $.get defines it. Consider making photos a global, then setting it in the $.get success function instead of setting it to 'a'. Inside the success function, you can then issue calls to other functions that would control displaying/processing the photos.

how can i get return value of javascript function [duplicate]

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 8 years ago.
my code like this
var key,value;
//……some code……
function checkReg(i,j){
$.getJSON(api_checkExists,{"k":i,"v":j,"rand":Math.random()},function(c){
alert(c.status);
return(c.status);
});
}
var temp=checkReg(key,value);
alert(temp);
The problem is when I run it in my browser, it always fist alert undefined then alert the return value; seems like that can not get the return value of function checkReg. I was so confused, what should I do?
That's because your ajax call is running asynch from the rest. Your code will already have returned before before the ajax is even triggered.
So the returning doesn't work like that, you should provide a callback to your function instead of trying to return it.
function checkReg(i,j, callback){
$.getJSON(api_checkExists,{"k":i,"v":j,"rand":Math.random()},function(c){
alert(c.status);
callback(c.status);
});
}
checkReg(key,value, function(temp){
alert(temp);
});
you cannot do that... since ajax is ashynchronus ... by the time the success function is called and return, the alert will be called thus having temp as undefined or empty.. one way to do this is doing the thing you need to inside the success called back of getJSON... or use $.deffered or callinga calback function..
function checkReg(i,j, callback){
$.getJSON(api_checkExists,{"k":i,"v":j,"rand":Math.random()},function(c){
callback(c.status);
});
}
checkReg(key,value, function(temp){
alert(temp);
});

Function return async response [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 7 years ago.
Like a person asked here (but his solutions as to call a nother function) https://stackoverflow.com/a/10796326/315200 ...I would like to know if its possible to have a function which doesn't call a second function on response of an async request, but simply return when the async request responses.
Something like this maybe:
function callToFacebook() {
var fbResponse;
FB.api('/me', function (response) {
fbResponse = response;
});
return fbResponse; //Will return undefined because CallToFacebook is async
}
Isn't that possible some way, without calling another function??
What I'm trying to achieve is to have one function I can call with some parameters, which will return the response object from a async webservice, like FB.
In short, no. You cannot have an asynchronous function return a meaningful value synchronously, because that value does not exist at that time (as it is built asynchronously in the background).
You can, however, return a Promise object, representing the "potential return value" of the asynchronous operation, and bind a function to that object using done() or similar. That way, your function gets return semantics (instead of having to chain the control flow into a callback), and remains asynchronous.
No, it's not possible.
You can't return value that is returned from async operation.
Think about it, you tell 10 people to have one mile running contest, they start now, will finish in one minute +-, but you want to know the answer now, it's not possible unless you're cheating...

Categories

Resources