javascript - 使用 map/reduce 和 jQuery 顺序运行任意数量的脚本

标签 javascript jquery asynchronous promise

我需要运行任意数量的脚本。下一个只能运行前一个已加载并执行的。我知道 RequireJS (及相关)将是正确的选择,但我正在尝试了解 Promise,所以这是我的实验:

var files = [
  'first.js',
  'second.js',
  'third.js',
  'fourth.js'
];

var funcs = files.map(function(file) {
  return function() { return $.getScript(file); }
});

var deferred = $.Deferred();

funcs.reduce(function (soFar, f) {
   return soFar.then(f);
}, deferred.resolve(funcs[0])); 

有人可以详细说明我的解决方案的陷阱和替代方案吗?

最佳答案

您真正要找的是.pipe (或者在 1.8+ 中,我相信 .then 被更改为表示相同的意思)

简而言之,管道将允许您以您正在寻找的方式链接 promise 。代码可能看起来像这样(未经测试):

var files, scriptsLoaded;

files = [ 'first.js', 'second.js', 'third.js', 'fourth.js' ];

while( files.length ) {
    (function() {
        var currentUrl = files.shift();

        scriptsLoaded = scriptsLoaded ?
            scriptsLoaded.pipe(function() {
                return $.getScript( currentUrl );
            }) :
            $.getScript( currentUrl );
    }());
}

$.when( scriptsLoaded ).done(function() {
    // All scripts are now loaded assuming none of them failed
});

** 编辑 **

通过您提供的链接,我了解您想要实现的目标。这是您的解决方案的更正版本,其中包含一些评论。它完成与其他解决方案相同的事情,但它是一个更简洁的版本:

var files = [ 'first.js', 'second.js', 'third.js', 'fourth.js' ];

// The initial value provided to the reduce function is a promise
// that will resolve when the first file has been loaded.  For each
// of the remaining file names in the array, pipe it through that first
// promise so that the files are loaded in sequence ( chained ).
// The value that is returned from the reduce function is a promise
// that will resolve only when the entire chain is done loading.
var scriptsLoaded = files.slice(1).reduce(function (soFar, file) {
    return soFar.pipe(function() {
        return $.getScript( file );
    });
}, $.getScript( files[0] ); 

关于javascript - 使用 map/reduce 和 jQuery 顺序运行任意数量的脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13093131/

相关文章:

jquery - 如何用jquery统计tr元素?

jquery - 简单的 jQuery(scrollTo 和 animate)在 IE 中不起作用

javascript - 停止并行运行的异步任务

javascript - 在 DC.js 中呈现多折线图

Javascript:将四舍五入的数字格式化为 N 位小数

javascript - 自动填充金额

javascript - nodejs 使用回调和事件

javascript - ng-bind-html 在我的上下文中不起作用

javascript - Meteor:循环模板的模板级别订阅或所有订阅完成时

javascript - 从多个延迟中获取结果并传递给函数