您真正要寻找的是.pipe(或在 1.8+ 中,我相信 .then 已更改为相同的意思)
简而言之,管道将允许您以您正在寻找的方式链接承诺。代码可能看起来像这样(未经测试):
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] );