无法理解此延迟代码

时间:2013-10-16 23:38:14

标签: jquery

我在这个帖子jQuery: load scripts in order

中遇到了这段代码
    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();

逐行,这段代码做了什么?

1 个答案:

答案 0 :(得分:1)

最初的问题是按顺序加载一组JS脚本,即逐个加载。 .then(以前为.pipe)的一个很好的属性是,当解决了回调返回的promise时,.then返回的新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();