This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 6 years ago.
I realize JavaScript callbacks have been explained over and over, but I don't seem to find a way to save values from an inner callback function.
request.get('http://google.com', function(error, response, body){
var $ = cheerio.load(body);
// Process HTML here
// How do I save the result from processing with a callback
}
// Or
var parse = function(error, response, body){
// Process HTML here
// Assign result to a variable or pass a callback to this function
};
request.get('http://google.com', parse);
I have multiple urls to process and I'd like to have one object summarizing the information afterwards.
By saving I mean either assigning to a variable or saving to a file.
Remember that the callback will be called when the async operation completes (like a second thread), meaning that the code after request.get will have been already executed then and you can't use return to send values back.
The solution is to make all the process inside the callback or to have other functions. Instead of returning the value, just make and call next_function(the_return_value) (something like that).
Related
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 5 years ago.
This method stores JSON objects retrieved from a firebase database to array scores.
function loadScoresToArray(){
databaseRef.orderByChild("Score").on("child_added", function (snap) {
scores.push(snap.val());
});
}
Run the above method and print content of scores
loadScoresToArray();
console.log(scores);
console.log(scores[0]);
output
As seen here, objects have correctly been added to scores.
But I can't retrieve them using index.
Reading similar questions like this I think this might be because when console.log(scores[0]); is called, the array is still empty. It has not been populated yet. This is just my guess.
How do I solve this? Is there a way to create a delay until the array is populated?
But I can't retrieve them using index.
That's because you're performing an asynchronous operation. Instead of waiting for the response, the execution continues immediately and the statement after the request call is execute.
How do I solve this? Is there a way to create a delay until the array
is populated?
No, don't use a delay. You can use a callback function.
function loadScoresToArray(callback){
databaseRef.orderByChild("Score").on("child_added", function (snap) {
scores.push(snap.val());
callback(scores);
});
}
loadScoresToArray(function(scores){
console.log(scores[0]);
});
Another solution is to use Promise constructor in order to perform an asynchronous operation.
function loadScoresToArray(){
return new Promise(function(resolve, reject){
databaseRef.orderByChild("Score").on("child_added", function (snap){
scores.push(snap.val());
resolve(scores);
});
});
}
loadScoresToArray().then(function(scores){
console.log(scores[0]);
});
Here are possible approaches in order to solve your problem.
Promises with async/await (ES2017+)
Callbacks
Promises with then() (ES2015+)
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 6 years ago.
I call my_function on form submit. The function looks inside a text file for the number entered by the user in my_input. If this number does not exist, the function pops an alert and should stop form submit.
My problem: the alert is shown, but when I close it, the form gets submitted. My problem is similar with this thread: How do I return the response from an asynchronous call?
One of the solutions there is to do the GET in plain javascript. Can someone help please? This is too advanced for me.
function my_function() {
$.get("http://www.example.com/file.txt", function(contents) {
var my_number = document.getElementById("my_input").value;
var hasString = contents.includes(my_number);
});
console.log(hasString); // **ALWAYS RETURNS UNDEFINED**
if (hasString == false) {
alert('Number does not exist in text file!');
return false;
}
}
hasString is a local variable of the callback function provided to $.get as second argument. This is why it's undefined outside said function. Note just moving the variable declaration to the outer scope won't fix the problem, as the callback function will be executed after the check hasString == false anyway (it will be executed when the get request finishes).
Answering your question more directly: either perform the get request synchronously (and properly declare the variable in the scope you need to use it) or restructure your code to use the information retrieved by the get request only inside the callback. Read the post #abc123 mentions for more information.
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 8 years ago.
There's probably an obvious mistake somewhere, but I just can't out find what's wrong.
I'm trying to retrieve data from an api, and use the js-function below to get it. If I do an alert(key) on the data inside the $.get-function, it alerts the correct data.
function getApiKey(company, password) {
var url = "http://myapi.com/" +company+ "?password=" +password;
var key = "";
$.get(url).done(function(data) {
key = data;
//alert(key) returns the correct data
});
return key;
}
However, I need to use the function in a different file, and that's where it doesn't work. When I do
var key = getApiKey("company", "password");
alert(key);
key is empty.
The $.get command is asynchronous, meaning that your function returns key with its initial value of "", then later when the async callback fires, it runs key=data.
You should read up on asynchronous behaviour in javascript - for a solution, you'll need some way to get the data back to the place of the call asynchronously. One such option is a promise.
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 8 years ago.
I am trying to access a variables inside a $.post jquery method. The code I have so far is below:
var fromDatabase;
$.post( "../read.php", function( data ) {
fromDatabase = JSON.parse(data);
console.log(fromDatabase); //this works fine
return fromDatabase;
});
console.log(fromDatabase); // but this gives me 0.
I am trying to get the from database variable so i tried to declare it outside the function to no avail.
Thank you.
You can't - you must continue program execution from within the callback, not immediately after the asynchronous $.post call.
You cannot return from an asynchronous function, that's the nature of asynchronicity. Instead, after your value is available (the callback function is called) you must work with the data within the scope of that function.
Perhaps a good starting point would be some Ajax tutorial. If you want more, simply google for JavaScript async.
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 8 years ago.
var response_var=""; // Added this line for debugging
ajax.onreadystatechange=function()
{
if(ajax.readyState==4 & ajax.status==200)
{
response_var=(ajax.responseText);
alert(ajax.responseText); // This alerts properly (some text).
return (ajax.responseText); // This is returning as undefined
}
}
return response_var; // This is empty if I add the line 1, if not in console it gives error response_var is not defined.
Why does not the response is getting stored in the variable or returned? I guess the scope of response_var ends within the onreadystatechange function so I tried return. But the value is undefined.
Ajax function always work out of sync with normal code flow ,hence the name "Asynchronous JavaScript and XML" .For Ajax required events you should not rely on return ,rather do your task immediately when you get your response from AJAX.