I can't access object inside array even though it exists [duplicate] - javascript

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+)

Related

Run a function against each object in an array in parallel? [duplicate]

This question already has answers here:
Wait until all promises complete even if some rejected
(20 answers)
Closed 2 months ago.
I have an array
var array = ["First","Second","Third"]
let i = 0;
I want it to run each object in the array across the same async functions at the same time
for (;i < arbAgainstLength;) {
const first = async () => {
//do some await stuff
}
const second = async (param1, param2) => {
//do other await stuff
}
}
This bot is monitoring price changes, so I'm looking for it to only take action on a specific object at the time that object meets the proper criteria.
So, if First meets the criteria, it will complete the rest of the sequence, but Second and Third will continue to listen.
Then, finally, once the sequence is complete for an object, I'd like to put that object BACK into the async functions.
Currently, and this is probably expected, the function only runs fully if it's the last object in the array
Is it possibly a forEach instead of a for? Or is a promise needed as well?
I have tried async.parallel and promises. If the answer is a promise, I think I may be still trying to grasp how they work exactly.
I think there was a lack of proper verbage in my question but I ended up finding that it was best used as a promise.all with a forEach inside it.
Thanks for all that!

How to show data outside of a subscribe scope/ how to use callback [duplicate]

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 3 years ago.
I want to show a list from an API call.
let url = 'api/list';
this.apiService.get<List[]>(url)
.subscribe((response) => {
this.list = response; // response has data
})
console.log(this.list); // no data shown
Because of async behavior the console always shows a blank list. How can I show the list with data outside of the subscribe scope. For clarification I need the list with data in the consoles position. I am familiar with the concept of callback. Do I need to use a callback function here? If yes, how can I achieve that?
The object the keyword this is pointing to is different in the places you are using it. So when you are setting this.list inside your callback function, you are setting the attribute list of your callback function.
One old skool way to fix this would be setting let that = this and then inside your callback function using that.list. By doing so you would be setting the attribute list of the keyword this that is one level above your callback function.
Hope it still makes some kind of sense.
Also look at Andrew Hills comment, it's full of logic :)

Saving values from JavaScript inner callback function [duplicate]

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).

JavaScript function returns empty string when a value is expected [duplicate]

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.

Trying to access a variable inside a jquery function [duplicate]

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.

Categories

Resources