當然,你可以這樣做的,這裏的一些僞代碼:
// 'feeds' is an array of the feed URLs
function grabFeeds(feeds) {
var index;
// We start with the first feed
index = 0;
// Kick off the process
feedWorker();
// Our "go get the next feed" function
function feedWorker() {
var feed;
// Do we have any more?
if (index < feeds.length) {
// Yes, request it and bump our index
// (You could combine these lines, but it's
// clearer to keep them separate)
feed = feeds[index];
++index;
start_feed_download(feed, callback);
}
}
// Our callback function
function callback() {
// ...do something with the result...
// Kick of the next feed (feedWorker is defensive,
// so we don't have to check index here)
feedWorker();
}
}
我不知道谷歌訂閱API,因此佔位符start_feed_download
功能。
做什麼是開始通過grabFeeds
函數抓取feed的過程,該函數接受一個feed數組。 grabFeeds
啓動feedWorker
,它啓動第一個提要請求,然後立即返回(幾乎可以肯定地在檢索到第一個提要之前)。 callback
處理結果,然後要求feedWorker
啓動下一個饋送請求(如果有)。
「魔術師」這裏是feedWorker
和callback
都是closures,所以儘管grabFeeds
已經回來了,index
和feeds
變量生活(在一個對象被稱爲「執行上下文」),只要任何引用執行上下文中的東西 - 在我們的例子中,直到callback
和feedWorker
不再被Google的東西引用。
謝謝,這沒有把戲。感謝關於閉包的更多解釋。現在閱讀它。 – Jan 2009-12-01 08:55:14