Asynchronous JavaScript: the right way to create loops?

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

? :-)

+4
1

?

Javascript , , , sync/async. :

.

. , .

Async , , , . - Array#extras

Array.prototype.asyncForEach = function asyncForEach(callback, context = null) {
  const self = this;
  let index = 0;
  
  function iterate() { setTimeout(iteration, 1500); }  
  function iteration() {
  
    callback.call(context, self[index], index, self);
    
    index += 1;
    if(self.length > index) {
      iterate();
    }
  }
  
  return iterate();
};

['hello dear', 'how are you?', 'I am fine, thanks']
  .asyncForEach((item, index, list) => {
  
    console.log(Date.now(), `Iteration at {i: ${index}}`, item);
  })
;

. , "Foo" 1000? 1000 "" .

, , , Javascript -, , .

( , ).

, , , Javascript!

+2

Source: https://habr.com/ru/post/1683229/


All Articles