0

我在这个线程jQuery中遇到了这段代码:按顺序加载脚本

    var deferred = new $.Deferred(),
        pipe = deferred;

    $.each(scripts , function(i, val) {
         pipe = pipe.pipe(function() {
             return  $.getScript(val, function() {
                 console.log('loaded '+ val);
             });
         });
    });

deferred.resolve();

一行一行,这段代码是做什么的?

4

1 回答 1

1

最初的问题是顺序加载一组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();
于 2013-10-17T02:48:29.107 回答