gpt4 book ai didi

javascript - 在回调函数中进行新的异步调用

转载 作者:行者123 更新时间:2023-11-30 13:42:18 25 4
gpt4 key购买 nike

我想使用 Google AJAX Feed API获取多个新闻源并将它们显示在网页上。

我不能使用 Google 的 FeedControl 类,因为我想控制提要项目的显示方式。这使我只能将 Google 的 Feed 类作为唯一的选择。

我已经让它与单个提要一起工作:提供一个 url 和一个回调函数;在回调函数中处理提要的结果。

我的问题:如何获取多个提要?我会以某种方式必须在回调函数中创建一个新的 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 函数获取提要的过程,该函数接受提要数组。 grabFeeds 启动 feedWorker,它启动第一个提要请求,然后立即返回(几乎可以肯定在第一个提要被检索之前)。 callback 处理结果,然后要求 feedWorker 启动下一个 feed 请求(如果有的话)。

这里的“魔法”是feedWorkercallback 都是closures ,因此即使 grabFeeds 已经返回,indexfeeds 变量仍然存在(在称为“执行上下文”的对象中)只要任何东西引用执行上下文中的东西——在我们的例子中,直到 callbackfeedWorker 不再被 Google 的东西引用。

关于javascript - 在回调函数中进行新的异步调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1600370/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com