Top community members
All Wiki Articles Create Wiki Article

Have you ever heard about encyclopedia for code?

What about: Wiki for Code project?

* because I've tried to share code and my solutions on different services and it was removed or I was unwelcomed
   - maybe it wasn't good place, but this one is.

if you think you have solution that can help someone, you are welcome to share this solution - Click here

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

0 contributions
12 points

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.
0 contributions

Checkout latest Findings & News:

Checkout latest questions:

Checkout latest wiki articles:

Hey šŸ‘‹
Would you like to know what we do?
  • Dirask is IT community, where we share coding knowledge and help each other to solve coding problems.
  • We welcome everyone,
    no matter what the experience,
    no matter how basic the question is,
    this community will help you.
Read more