JSFiddle - React, Tailwind, and code Playground

by riemersebastian

HTML

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.1/angular.min.js"></script>
<div ng-controller="MyCtrl">
  Hello there!
    <br>
    <br>Please check the console.log to see the order of printed out text ...
    <br>
    <br> Question 1: Is this the correct way of chaining async calls?
    <br> Question 2: Is the resulting order of outputs in the console random or is it guaranteed that the last block will always be executed last?
    <br> Question 3: How can I, for simulation purposes, delay the defer.resolve() within the writeSome function for the FOR-loop calls, so I can be sure the calls are really chained correctly and the result is not randomly correct?
</div>

JavaScript

var myApp = angular.module('myApp',[]);

// in real case, this is writing to a file which I want to wait for
function writeSome($q, text) {
            var defer = $q.defer();
            console.log("writeSome: " + text);
               
            defer.resolve();                
            // Delaying the resolve here does not work, why? No further code is executed if I try it like that.
            //setTimeout(function() { defer.resolve()}, 1000);            
            
    
            return defer.promise;
};

// in real case, this is reading some JSON from file which I want to wait for
function readSome($q, $scope) {
    var defer = $q.defer();
    console.log("readSome ...");    
    defer.resolve();
    return defer.promise;
}

// this is the function called from the template
function outerFunction($q, $scope) {
    var defer = $q.defer();    
    readSome($q,$scope).then(function() {
        var promise = writeSome($q, $scope.testArray[0])
        for (var i=1; i < $scope.testArray.length; i++) {
             promise = promise.then(
                 angular.bind(null, writeSome, $q, $scope.testArray[i])
             );                                  
        } 
        // this must not be called before all calls in for-loop have finished
        promise = promise.then(function() {
            return writeSome($q, "finish").then(function() {
                console.log("resolve");
                // resolving here after everything has been done, yey!
                defer.resolve();
            });   
        });        
    });   
   
    return defer.promise;
}

function MyCtrl($scope, $q) {
    // prepare some data for testing 
    $scope.testArray = [];
    $scope.testArray.push(1);
    $scope.testArray.push(2);
    $scope.testArray.push(3);    
        
    outerFunction($q, $scope).then(function() {
        // in real case, some reloading is done here which depends on 
        // all save operations being done BEFORE reloading
       ...