在回调函数中进行新的异步调用
-
05-07-2019 - |
题
我想使用 Google AJAX Feed API 用于获取多个新闻源并将其显示在网页上。
我无法使用Google的FeedControl类,因为我想控制Feed项目的显示方式。这使得Google的Feed类成为唯一的选择。
我已经使用单个Feed:提供网址和回调功能;处理回调函数内部的feed结果。
我的问题:如何获取多个Feed?我会以某种方式在回调函数中创建一个新的google.feeds.feed对象并为其提供一个新的url和...相同的回调函数(?)
我从未学过计算机科学,所以这种递归让我头晕目眩。 任何人都可以解释我必须做什么?
解决方案
当然,你可以这样做,这里有一些伪代码:
// '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();
}
}
我不知道Google Feed API,因此占位符 start_feed_download
函数。
它的作用是开始通过 grabFeeds
函数获取Feed的过程,该函数接受一组feed。 grabFeeds
启动 feedWorker
,启动第一个Feed请求,然后立即返回 (几乎可以肯定在检索到第一个Feed之前)。 callback
处理结果,然后要求 feedWorker
启动下一个请求(如果有的话)。
“魔法”这里 feedWorker
和回调
都是闭包,所以即使 grabFeeds
已经返回, index
和 feeds
变量仍然存在(在一个名为“执行上下文”的对象中),只要有任何内容引用执行上下文中的内容 - 在我们的例子中,直到 callback
和 feedWorker
为止更长时间被谷歌的东西引用。
其他提示
是的,你可以这样做,只要确保每当你做递归时你有两种情况(a)基本情况和(b)递归情况。
仅在第二种情况下,函数调用自身,确保不在基本情况下,否则最终会得到无限递归。例如,在这个阶乘函数中,0是基本情况,其他一切都是递归情况
function fact(n) {
if (n==0) { return 1; }
else { return n * factorial(n-1) }
}
或者,你可以一次做一个,即。启动第一个,然后启动第二个,而不是在第二个开始加载之前必须等待一个完全加载。