shabashj
8/23/2016 - 11:20 AM

Promise basic example with requirejs (q.js and require.js should be in scripts folder)

Promise basic example with requirejs (q.js and require.js should be in scripts folder)

"use strict";

require(["scripts/q"], function (Q) {
    
    /* Scenario when promise is required */        
    /*log1(); log2();
    
    function log1() {
        setTimeout(function () {
            console.log("Log 1");
        }, 2000);
    }*/
    
    // Wanted programm flow
    log1().then(log2);
    
    // Change log1() to support promise
    function log1() {
        var deferred = Q.defer();
        setTimeout(function () {
            console.log("Log 1");
            deferred.resolve();
        }, 2000);
        return deferred.promise;
    }

    function log2() {
        console.log("Log 2");
    }
});
<!DOCTYPE html>
<html>

<head>
    <script src="scripts/require.js"></script>
    <script src="scripts/test.js"></script>
</head>

<body>

</body>

</html>