JSFiddle - React, Tailwind, and code Playground

HTML

<script type="text/javascript" src="https://code.jquery.com/jquery-2.1.3.js"></script>
<script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/q.js/0.9.2/q.js"></script>

JavaScript

function promiseWhile(condition, body) {
    var done = Q.defer();
    function loop() {
        // When the result of calling `condition` is no longer true, we are
        // done.
        if (!condition()) return done.resolve();
        // Use `when`, in case `body` does not return a promise.
        // When it completes loop again otherwise, if it fails, reject the
        // done promise
        body().then(loop);
    }
    // Start running the loop in the next tick so that this function is
    // completely async. It would be unexpected if `body` was called
    // synchronously the first time.
    loop();
    // The promise
    return done.promise;
}

// Usage
i = 0
promiseWhile(function () { return i < 5; }, function () {
    console.log(i);
    i++;
    var deferred = Q.defer();
    setTimeout(function () {
        deferred.resolve(new Error("HELP! :("));
    }, 1000);
    return deferred.promise;
}).then(function () {
    console.log("done");
}).done();