I've come across a situation where I have an asynchronous function inside of a for loop. I've done my prerequisite searching and now know that forEach() or map() might be the solution I need. But all of the examples I see just console.log() the result of each async function. How would it work to have to set the results of each async function into a variable, and then only return the variable?
Here's some slimmed down code of what I'm doing: (this is all in node, by the way)
var clients={
"102323":{stuff about this client},
"242341":{stuff about that client}
};
var messages={};
for (var id_client in clients) {
mysql.query("SELECT * FROM messages WHERE id_client='"+id_client+"' ORDER BY date", function(err, rows) {
if (typeof rows !== 'undefined') messages[id_client]=rows;
});
}
//do other stuff with messages variable
With this, messages predictably is null. Which I understand.
But even when I transition this to using map() instead of for(), like this...
var messages={};
Object.keys(clients).map(function(id_client){
mysql.query("SELECT * FROM messages WHERE id_client='"+id_client+"' ORDER BY date", function(err, rows) {
if (typeof rows !== 'undefined') messages[id_client]=rows;
});
});
...messages ends up being null.
Finally, just want to note that I do know how to wrap mysql.query() into another function with a callback and all that to get around the whole asynchronous thing. I just don't know how that all works if being iterated on inside of a loop.
id_clientwill be "correct" for each iteration of .map ... in the for loop, it would be the last client every timemessageswill be populated - i.e. well after the next line of code (not shown in either snippet)mysql.query("SELECT * FROM messages WHERE id_client = ? ORDER BY date", ['id_client'], function(err, rows) {