0

I am trying to understand this piece of code

    require(['mifosXComponents'], function (componentsInit) {
        componentsInit().then(function(){
            require(['test/testInitializer'], function (testMode) {
                if (!testMode) {
                    angular.bootstrap(document, ['MifosX_Application']);
                }
            });
        });
    });

The code is at mifosX client code. I believe this is the entry point of the mifosX web client software. I am really confused by the require syntax here. All the online sample code I have seen is like require(["a", "b"], function (a, b){});. In the other words, the parameter list inside the function() are all listed inside the dependence [] right before it. However the code I pasted above has componentsInit inside the function(). And I could not find any place in the source code tree that componentsInit gets defined.....

What I am trying here is to understand the code logic flow of mifosX. I am new to Javascript and RequireJS. Please help me understand this if you know what's going on here. Thanks in advance!

Max Li
  • 551
  • 2
  • 14
  • It's defined on line 1 of your code: `function (componentsInit)` is where it is defined. The required package/library/whatever returns a [promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise). – Daedalus Mar 13 '20 at 06:49
  • Thanks for the reply, I have another question how to understand the `then()` in `componentsInit().then(function()`? `componentsInit()` is just defined, where the member `then()` comes from? Or is it actually defined at line 2? – Max Li Mar 13 '20 at 07:50
  • Click the link I gave, it's all explained there. – Daedalus Mar 13 '20 at 07:52

1 Answers1

2

Here is your code with some comments which will clarify:

// in the first line you are requiring a module with id `mifosXComponents`
// which then is passed to the callback as `componentsInit`
require(['mifosXComponents'], function (componentsInit) {
    // seems that `componentsInit` is a function which returns a Promise object,
    // so your are passing a callback to it to execute it after its fulfilment 
    componentsInit().then(function(){
        // when the promise is fulfilled, you are requiring another module
        // with id `test/testInitializer` which is passed to callback as `testMode`
        require(['test/testInitializer'], function (testMode) {
            // next lines are pretty simple to understand :)
            if (!testMode) {
                angular.bootstrap(document, ['MifosX_Application']);
            }
        });
    });
});

About Promise you can read here: What does the function then() mean in JavaScript?

Damian Dziaduch
  • 2,107
  • 1
  • 15
  • 16