RequireJS: nested calls

I have a scenario where I have nested require () calls to load different modules.

Is there any way I can guarantee that all calls to require () and all its require () requests will be fully loaded before calling the callback function?

Is there a way to indicate that require () calls are synchronous?

function someFunction(callback) {

  //top level require
  require([...], function(...) {

     //nested require
     require([...], function(...) {
     });

     //nested require
     require([...], function(...) {
     });

  });

  callback();
};
+5
source share
2 answers

You need to execute callbackin the last function require(...):

function someFunction(callback) {
   require(['somemodule'], function(someModule) {
     // do stuff with someModule...

     // execute callback
     callback(); 
   });
}

What you can also do is specify your dependencies with the define function .

Example:

define('somemodule', ['somedependency'], function(someDependency) {
   // return somemodule
   return {
     someProperty: someDependency.getProperty();
   };
});

function someFunction(callBack) {
   var someModule = require('somemodule');   
   var foo = someModule.someProperty;

   return callBack(foo);
}
+3
source

There is a way to make requirecall synchronization. Make CommonJS style:

var module = require('modulepath')

, factory , "" ... .

AMD requre(depsArray, factoryFn) , . "", "" .

, A B . - , " " define:

function someFunction(callback) {

  var resultOfOuterCode = someResultOfCalculations

  //top level require
  require([...], function(...) {

    var resultOfTopRequireCode = someOtherResultOfCalculations

    var semaphore = {
      'count': 2 // represents the number of thread that need to be "done" before 
      , 'callback':callback // this callback is fired.
      , 'checkIfLast': function(){
        this.count -= 1
        if (!this.count) {
          // count is now 0 - time to run our callback
          this.callback()
        }
      }
    }

    //nested require A
    require([...], function(...) {
      // using resultOfTopRequireCode // <-- !!!! this is important part
      ...
      semaphore.checkIfLast()
    });

    //nested require B
    require([...], function(...) {
      // using resultOfTopRequireCode // <-- !!!! this is important part
      semaphore.checkIfLast()
    });

  });

};

, require (dependArray, factoryFn) "" .

+2

All Articles