Last few days I'm thinking about JavaScript. Lot of frameworks offer functions only in asynchronous/promises way. But as I'm used to program in synchronous languages (PHP, Python, ...), I struggle with some basic ideas.
For example:
How to make loops with asynchronous function properly?
Let's say we have function nextValue() which returns string from some list of words. Our task is find word "Foo" in this list and print the index where the "Foo" word is located.
If the nextValue() function was synchronous, we could do it very easy:
var found = false;
for (var i = 0; !found; i++) {
if (nextValue() == 'Foo') {
console.log("'Foo' found at index " + i);
found = true;
}
}
But if the function was asynchronous, the only idea I've got is to make function and call it recursively until we find the "Foo" word:
var i = 0;
(function checkNextValue(){
nextValue(function(value){
if (value == 'Foo') {
console.log("'Foo' found at index " + i);
} else {
i++;
checkNextValue();
}
});
})();
But I see few problems here:
- The asynchronous example is much harder to read. Imagine if we needed two nested loops or even more.
- RAM usage. What if the "Foo" value will be at index 1000? There will be 1000 running functions in the memory "thanks" to the recursion.
- And it's complicated in general and much harder to write the code, or even re-use the code in another place (we can't simply
returnvalue, we are forced to use callback or promise again).
What am I missing here? Thanks for you ideas :-)
async/awaitsyntax is attempting to simplify that. No, since the callbacks are asynchronous you won't have 1000 functions "running in RAM".