系统JS在一个呼叫中加载多个依赖关系



查看SystemJS的文档,我找不到同时加载多个依赖项的示例。我期望API像...

System.import(['jquery.js','underscore.js']).then(function($, _) {
    // ready to go with both jQuery and Underscore...
});

我希望它会使用承诺并行加载所有依赖项,并在所有依赖性并行执行回调。这可能吗?如果没有,是否有没有实现此功能的原因?

这是有可能的。

Promise.all([
    System.import('jquery'),
    System.import('underscore')
]).then(function(modules) {
    var jquery = modules[0];
    var underscore = modules[1];
});

,但正如您所看到的那样丑陋。有话要说考虑允许在规格级别上像您的示例这样的数组,但是由于这是一个规格,因此需要在模块规格中。

更好的替代方法实际上是只有一个用于应用程序的入口点,app.js,然后具有负载依赖项。

这就是我要做的方式,习惯了它:未测试。

var SystemImport = System.import;
System.import = function (name, options) {
    if (Object.prototype.toString.call(name) !== '[object Array]')
        return SystemImport.apply(this, arguments);
    var self = this,
        imports = Promise.all(name.map(function (name) {
            return SystemImport.call(self, name); // should i pass options ?
        }));
    return {
        then: function (onfulfill, onreject) {
            return imports.then(function (dependencies) {
                return onfulfill.apply(null, dependencies);
            }, onreject);
        }
    };
};

此片段将用包装版本的版本替换System.import,以便使用依赖项数组。

它返回一个"当时的"对象,这应该可以通过任何合规的承诺实施来正常工作。

由于.spread方法不在Promise A Spec中,这是我能想到的最规范的方法...

最短,最干燥的方法可能是将[].map()应用于System.import,然后破坏其结果:

Promise.all([
    'jquery',
    'underscore'
].map(url => System.import(url))).then(function ([$, _]) {
    // do stuff with results
});

请记住,在撰写本文时,破坏仍然需要进行。

如果您不想转移,则可以编写自己的包装纸并传播脚本:

function spread(callback) {
    return function (args) {
        return callback.apply(undefined, args);
    }
}
function import(deps) {
    return Promise.all(deps.map(function (url) {return System.import(url);}));
}

并加载它:

import(['jquery', 'underscore']).then(spread(function ($, _) { /*...*/ }));

我正在寻找同一件事。我目前正在使用bluebird,Promise.ly和Promise。那就像我能写的那样"不错"。

Promise.all([
  SystemJS.import('jquery'),
  SystemJS.import('axios')
]).spread(function(jquery, axios){
  return jquery < axios;
});

最新更新