In the last few days, I have been thinking about JavaScript. Many frameworks offer functions only in asynchronous / promises mode. But since I'm used to programming in synchronous languages (PHP, Python, ...), I struggle with some basic ideas.
For instance:
How to create loops with asynchronous function?
Let's say we have a function nextValue()that returns a string from some list of words. Our task is to find the word "Foo" in this list and print the index where the word "Foo" is located.
If the function nextValue()was synchronous, we could do it very simply:
var found = false;
for (var i = 0; !found; i++) {
if (nextValue() == 'Foo') {
console.log("'Foo' found at index " + i);
found = true;
}
}
Run code, , , , "Foo":
var i = 0;
(function checkNextValue(){
nextValue(function(value){
if (value == 'Foo') {
console.log("'Foo' found at index " + i);
} else {
i++;
checkNextValue();
}
});
})();
:
- . , .
- . , "Foo" 1000? 1000 "" .
- (
return , ).
? :-)