Search code examples
javascriptpromisesystemjs

how can I write this module import/promise routine in the least amount of code?


I'm implementing SystemJS to import external js modules. I'd like to define my module names in a string array and then implement a custom promise routine after all of the modules have been imported. Looking to implement something like this:

var modules = 
[
   'MyModule1',
   'MyModule2',
   'MyModule3'
];

$.each(modules, function(i, module)
{
  return SystemJS.import(module + '.js');
})
.then(function(){
  //post import processing
});

The code above doesn't work but it demonstrates the basic idea of what I'm trying to achieve.


Solution

  • Use Promise.all

    Promise.all(modules.map(module=>SystemJS.import(module + '.js'))
    .then(function(){
        // all loaded here
    });
    

    Of course, the documentation for SystemJS shows this exact method - that's what documentation is for