turn require() into a promise

by fiddlegrimbo

HTML

<script>
require = {
    paths: {
        "jquery": "http://code.jquery.com/jquery-2.0.3",
        "mymodule": "https://rawgithub.com/gitgrimbo/5689953/raw/9b44d7e5f504b2245331be3ed3fcbb7bf8635da6/gistfile1"
    }
};
</script>
<script src="//cdnjs.cloudflare.com/ajax/libs/require.js/2.1.8/require.min.js"></script>
<button>click me</button>

JavaScript

function dfdRequire(deps) {
    return $.Deferred(function(dfd) {
        require(deps, function() {
            dfd.resolve.apply(dfd, arguments);
        });
    }).promise();
}

define("app", ["jquery"], function($) {
    return {
        doSomething: function(value) {
            console.log("doSomething with " + value);
        },
        getSomething: function() {
            // Load the dependency as a promise, and return that promise to the caller,
            // so the caller can also await its resolution.
            return dfdRequire(["mymodule"]).then(function(mymodule) {
                console.log("Loaded mymodule. Value=" + mymodule);
                // return the module value as-is,
                // or optionally perform some transformation.
                return mymodule.toUpperCase();
            });
        }
    };
});

require(["jquery", "app"], function($, app) {
    console.log($.fn.jquery);
    $("button").first().click(function(evt) {
        console.log(evt);
        app.getSomething()
            .done(console.log.bind(console))
            .then(app.doSomething.bind(app));
    });
});