node.jscordovarequirejsrequirejs-optimizer

Make Cordova wait for async hook to finish


In my Cordova project, I have a hook which does RequireJS optimization (r.js) on after_prepare. That optimization is inherently asynchronous, so my hook code returns before all optimization is fully finished.

For example, this causes issues when running cordova run browser: On the first page load, optimization has not finished yet and the site looks broken.

Is there a way to make the Cordovoa build process to block until a certain hook fires a callback? Or can the optimizer be run in a blocking/sync way?

An alternative I could think of is using a different process for optimization and busy-wait in the main for it to finish, but that looks like an overkill and bad practice to me.


Solution

  • You can use the built-in promise module to block Cordova from proceeding until the hook has resolved. Something along these lines:

    #!/usr/bin/env node
    
    var deferral;
    
    function doSomethingAsync(){
        somethingAync
            .success(function(){
                deferral.resolve();
            })
            .fail(function(err){
                deferral.reject(err);
            });
    }
    
    module.exports = function(ctx) {
        deferral = ctx.requireCordovaModule('q').defer();
        doSomethingAsync();
        return deferral.promise;
    };