2013-10-16 40 views
0

我碰到這段代碼在此線程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

你可能想知道,從jQuery 1.8開始,'.pipe()'不推薦使用,應該用'.then() '。 – jfriend00

+0

好的謝謝。你能解釋一下代碼在做什麼?我知道它是在其他加載後調用一堆腳本,但如果我繼續並逐行閱讀代碼,我不知道發生了什麼 – Sasikaran

+0

如果我自己理解它,我會做出答案,但是我不知道。 – jfriend00

回答

1

最初的問題是按順序加載一組JS代碼,即逐個加載。 .then(之前爲.pipe)的一個不錯的屬性是當回調返回的許諾得到解決時,由.then返回的新許諾得到解決。

一個小例子:

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();