当然,你可以这样做的,这里的一些伪代码:
// '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