最初的问题是顺序加载一组JS脚本,即一个接一个。.then
(previously .pipe
) 的一个很好的属性是,.then
当回调返回的 promise 被解析时,返回的新 promise 被解析。
一个小例子:
var promiseA = promise.then(function() {
return promiseB; // assume this is defined somewhere
});
在这里,promiseA
解决一次promiseB
就解决了。我们可以使用这个属性来顺序执行异步函数。如果要依次加载三个脚本 A、B 和 C,可以执行以下操作:
load(A).then(function() {
// executed when promise returned by load(A) is resolved
return load(B);
}).then(function() {
// executed when promise returned by load(B) is resolved
return load(C);
});
这就是上面的代码所做的,只是针对可变数量的脚本:
// create a new deferred object
var deferred = new $.Deferred(),
// assign it to a new variables to keep a reference to the original deferred object
// so that we can resolve it later
pipe = deferred;
// iterate over an array of URLs
$.each(scripts , function(i, val) {
// for each URL do this
// overwrite the `pipe` variable with the new promise so that
// the next iteration can use the new promise
pipe = pipe.pipe(function() {
// this is executed when the (i-1)th script loaded
// load the ith script
return $.getScript(val);
});
});
// resolve the original (first) promise
deferred.resolve();
也许循环让你感到困惑。如果您有固定数量的脚本,则相当于:
var deferred = new $.Deferred();
var pipe = deferred;
pipe = pipe.then(function() {
return $.getScript(scripts[0]));
});
pipe = pipe.then(function() {
return $.getScript(scripts[1]));
});
pipe = pipe.then(function() {
return $.getScript(scripts[2]));
});
deferred.resolve();