Languages
[Edit]
EN

JavaScript - how to make each loop iteration on async callback/response?

12 points
Created by:
elmer
646

Using JavaScript it is posssible to write own class that helps to make async iterations on callback in following way.

1. Custom loop class example

Read this article to see async loop class example.

2. AJAX response based example

Note: this approach is useful with AJAX requests.

// ONLINE-RUNNER:browser;

<!doctype html>
<html lang="en">
<head>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
  <script>
    
    var timer = new Timer();

    function Timer() {
        var t1 = new Date();

        this.getTime = function() {
            var t2 = new Date();

            return t2 - t1;
        };
    }

    function printMessage(message) {
        var time = timer.getTime();

        console.log('[' + message + ', time=' + time + ']');
    }
    
  </script>
</head>
<body>
<pre id="response"></pre>
<script>

    var response = document.querySelector('#response');

  	var i = 0;
  	var links = [
    	'/examples/echo?text=Hello1!',
      	'/examples/echo?text=Hello2!',
      	'/examples/echo?text=Hello3!'
    ];

    function makeRequest(i) {
      	if(i < links.length) {
          printMessage('loop iteration ' + i);

          // success and error methods are callbacks of AJAX request

          $.ajax({
              type: 'GET',
              url: links[i],
              success: function (data) {
                  response.innerText += data + '\n';
                  makeRequest(i + 1); // callback for next iteration
              },
              error: function (error) {
                  // in this case doing nothing breaks loop
                  printMessage('loop finished');
              }
          });
        } else {
          	printMessage('loop finished');
        }
    }

  	printMessage('loop started');
	makeRequest(0);
	
</script>
</body>
</html>

3. async/await based example

// ONLINE-RUNNER:browser;

<!doctype html>
<html lang="en">
<head>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
  <script>
    
    var timer = new Timer();

    function Timer() {
        var t1 = new Date();

        this.getTime = function() {
            var t2 = new Date();

            return t2 - t1;
        };
    }

    function printMessage(message) {
        var time = timer.getTime();

        console.log('[' + message + ', time=' + time + ']');
    }
    
  </script>
</head>
<body>
<pre id="response"></pre>
<script>

    var response = document.querySelector('#response');

    var i = 0;
  	var links = [
    	'/examples/echo?text=Hello1!',
      	'/examples/echo?text=Hello2!',
      	'/examples/echo?text=Hello3!'
    ];

    function coverAjax(i) {
      	var promise = new Promise(function(resolve, reject) {
        	 $.ajax({
                type: 'GET',
                url: links[i],
                success: function (data) {
                    response.innerText += data + '\n';
                    resolve(); // callback for next iteration
                },
                error: function (error) {
                    reject(); // callback to break loop
                }
            });
        });
      
      	return promise;
    }

  	(async function() {
        printMessage('loop started');
      
      	try {
            for (var i = 0; i < links.length; ++i) {
                printMessage('loop iteration ' + i);

				await coverAjax(i);
            }
        } catch(e) {
            console.log('[ajax error]');
        } finally {
            printMessage('loop finished');
        }
    })();

</script>
</body>
</html>

Notes: 

  • Promises have been introduced in ES2015.
  • async/await keywords has been introduced in ES2017.
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join