Languages
[Edit]
EN

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

12 points
Created by:
AnnLen
1771

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.
Hey 👋
Would you like to know what we do?
  • Dirask is a friendly IT community for learners, professionals and hobbyists to share their knowledge and help each other in extraordinary easy way.
  • We welcome everyone,
    no matter what the experience,
    no matter how basic the question is,
    this community will help you.