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 6 years ago.
When getting data from a text file, it seems to take a while. With the first console.log the result is undefined, after waiting some time and then running console.log the data shows.
var msg;
$.get("./whazzup.txt", function(text) {
msg = text;
});
console.log(msg);
setTimeout(function(){ console.log(msg); }, 3000);
How would I go about only running code once the callback is complete?
Just move the console.log() into the "done" callback function because you can't know exactly when or if it will complete. This is the point of the "done" callback function - - to defer work that needs to be done after a successful call has been made.
JavaScript promises (or JQuery deferreds) could also be used to disconnect the callback(s) from the initial AJAX request for more flexibility, but the nature of AJAX stays the same.
$.get("./whazzup.txt", function(text) {
// This function will only be executed when the AJAX call has successfully completed
msg = text;
console.log(msg);
});
// This one was working, because you are basically telling the JavaScript
// runtime to wait 3 seconds (at least) before writing the message and by
// that time the AJAX call has completed. But, this technique is not
// reliable because there may be times when the AJAX call hasn't completed
// after 3 seconds. You just can't know how long it will take.
setTimeout(function(){ console.log(msg); }, 3000);
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:
Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference
(7 answers)
Closed 6 years ago.
When I run this, the variable elevationPoint is undefined on the first alert. I noticed by accident that it works on the second alert. Why is that?
var elevator = new google.maps.ElevationService();
var coordinates = new google.maps.LatLng(closestLat , closestLng);
var pointElevation;
elevator.getElevationForLocations({
'locations':[coordinates]
}, function (results, status) {
if (status == google.maps.ElevationStatus.OK) {
// Retrieve the first result
if (results[0]) {
pointElevation = results[0].elevation;
} else {
alert('No results found');
}
}
else {
alert('Elevation service failed due to: ' + status);
}
});
alert(pointElevation);
alert(pointElevation);
The fact that you pass a callback to API that you are using makes me think that it is asynchronous.
When you make the first alert the asynchronous task has not completed yet . By the time the second alert fires the callback has completed and you get the expected value on the variable that youbexoex. Try moving the alert inside the function you pass to the API and it should work.
Regards
Edit to clarity the blocking/non-blocking topic
Functions requiring callbacks are usually asynchronous,and they run on a separate thread called the eventLoop. The code is executed immediately after evaluation, so your API call fires immediately and it is placed on the event loop. When the first alert is reached the asynchronous operations are already on the eventLoop, so although the alert is blocking it can not block the code running on a separate thread. When the second alert is executed the asynchronous code has already completed and the callback executed ,that's why you can see the value on the second alert .
I recommend you investigate about the event loop and how it works
This is a fantastic visual explanation https://m.youtube.com/watch?v=8aGhZQkoFbQ
Because pointElevation is defined inside an asynchronous call getElevationForLocations(). By chance the 2nd alert works it is because the async call has finished by then, but it is not guaranteed.
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!
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 8 years ago.
Here's my script which I type into Firebug:
var jsonData;
$.getJSON("./js/ohno.JSON",function(data){
jsonData = data;
});
console.log(jsonData);
Here's the .JSON file contents:
{"oh":"no"}
The first time I run the script in Firebug, it returns "undefined"
The second time I run it (without refreshing the page) it returns the Object.
If I refresh, the same thing happens -- first time running returns "undefined", and second time running it returns the Object.
The .JSON file is
How do I make it so that it returns the Object the first time I run the script?
getJSON is async; meaning that script execution will continue, while it still loads the data.
You have to wait until it finishes.
var jsonData;
$.getJSON("./js/ohno.JSON",function(data){
jsonData = data;
console.log(jsonData);
});
You need to place the console.log (and any other code you want to run on data) inside the callback function:
$.getJSON("./js/ohno.JSON",function(data){
jsonData = data;
console.log(jsonData);
});
You can also use .ajaxComplete if you feel the need to keep it separate.
getJSON is asynchronous, which is why you have to provide a callback to handle the data. The request is fired off, but it hasn't completed by the time you get to your console.log, so the value is undefined. It finishes a short time later and sets the variable.
Move your console.log handler into your callback, and all should work as expected.
The anonymous function is an asynchronous callback, so it gets called after your console.log.
Here is the right way to do it :
var jsonData;
$.getJSON("./js/ohno.JSON",function(data){
jsonData = data;
console.log(jsonData);
});
The getJSON function is asynchronous, so the success callback function only gets executed once the request finishes. Your console.dir() is initially executing before the response happens.
Put the console.dir() inside your getJson handler function.