Iterating a list of asynchronously processed items recursively (replacement for `setInterval`)

This demo demonstrates how one could possibly run an iteration recursively on a list of items once asynchronous operations on all of the items is finished. This rids you of the need to perform the iteration using something like `setInterval` as there is no guaranty that one iteration was completely over when the next one was started.

by Ahmad Baktash Hayeri

HTML

<script src="//cdn.jsdelivr.net/bluebird/3.4.0/bluebird.js"></script>
<h1 id="waitFlag">
    Started
</h1>
<h3 id="counter">
    
</h3>

JavaScript

var waitFlag = document.getElementById('waitFlag'),
counter = document.getElementById('counter'),
i = 0;

function run(){
    console.log('promise resolved');
        var items = [1, 2, 3, 4, 5, 6, 7];

        items.reduce(function(promise, item){
            return promise.then(function(result){
                counter.innerHTML = item;
                return doAsyncOperation();
            });
        }, Promise.resolve())
        .then(function(){
        	++i;
            waitFlag.innerHTML = "Iteration #" + i + " finished, initiating next...";
            run();
        });
};


function doAsyncOperation(item, result){
	return new Promise(function(resolve, reject){
    	setTimeout(function(){
        	var response = item;
        	resolve(response);
        }, 1000)
    });
}

run();