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.
Related
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 1 year ago.
I have a function which is returning information from an API call,part of which is an access token. I then need to plug that access token into the parameters of a redirect URL. Only problem is that thw redirect is invoked before the data is returned. Any ideas on how I can wait till the data is returned before invoking the redirect?
Here's the code:
oauthClient.createToken(req.url)
.then((authResponse) => {
oauth2_token_json = JSON.stringify(authResponse.getJson(), null,2);
let newToken = JSON.parse(oauth2_token_json)
accessToken = newToken.access_token
})
.catch((e) => {
console.error(e);
});
res.redirect(`http://localhost:3000/?token=${accessToken}`)
});
Add one more .then() and make sure the previous .then() returns the authToken (or any variable). Now run that logic of res.redirect(..).. in the next nested .then().
This way you are making sure, the code waits for the asynchronous part to finish off first. then-ables are the best way to make sure your code only runs once the promise is resolved. JavaScript executioner jumps to next line of code once it sees a asynchronous code block, i.e., could be a promise, .then()s, async-awaits.
This was the reason why, res.redirect() was running a little earlier.
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 3 years ago.
I use an ajax call to get the value of timer from the server. And I have to use that value for timeout in setTimeout() method. How to use functions instead of an actual value.
Here is my code:
if(isStopped) {
setTimeout(stopLoading, getTimerValue());
console.log("Stopped loading image");
}
getTimerValue() is my ajax call to the server. It works fine if I use an value like 5000 instead of the function. Please help me to solve this. Thanks in advance!
Update - Solved:
There was an issue with my ajax call. It was returning undefined. After adding callback option, it works fine.
Please check this example.
var isStopped = true;
function getTimerValue() {
return 5000;
}
function stopLoading() {
console.log('ok')
}
if(isStopped) {
setTimeout(stopLoading, getTimerValue());
console.log("Stopped loading image");
}
As i set isStopped to true so its insert the if condition then its set the setTimeout function. but as i set it to execute it after 5000 so it will wait in the mean time it will execute the next line console.log("Stopped loading image"); and the after 5000 it prints ok
Hope This will help
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 6 years ago.
I know the title is a bit vague but I don't know how else to ask this and I'm having trouble wrapping my head around async javascript.
I'm writing a nodeJS app and I want to write a function that takes some xml input, converts it to JSON, cleans it up a bit, and returns it. I'm using the xml2js module to achieve this but I'm having some trouble because xml2js is asynchronous. Here's is a simplified version of my code:
function cleanUpData(xmlData) {
xml2js(xmlData, xml2jsCallback);
function xml2jsCallback(err, result) {
// do a bunch of additional cleanup
return cleanedUpJSON;
}
}
What I want is to be able to pass the xml to the cleanUpData function and get back the nice JSON, but since xml2js() is async, I can't really do that. I would need to do everything else I want to do inside the xml2jsCallback() function and no value would ever be returned. I'm just trying to write a simple utility function though. Is the answer that I just can't use xml2js for this purpose? I'd really appreciate some insight because I'm pretty sure I must be unfamilair with some js coding pattern that will accomplish what I need.
Callback syntax:
function cleanUpData(xmlData, callback) {
xml2js(xmlData, function(err, result){
callback(result);
});
}
cleanUpData(xmlData, function(jsondata){
// do stuff here with jsondata
});
Promise syntax:
function cleanUpData(xmlData) {
return new Promise(function(done){
xml2js(xmlData, function(err, result){
done(result);
});
});
}
cleanUpData(xmlData).then(function(jsondata){
// do stuff here with jsondata
});
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.
});
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!