我正在处理三个嵌套函数,最后一个函数没有返回我想要的项目列表。如果我从循环内部记录最后一个函数的控制台结果,我会看到我想要的 URL,但仅限于该函数的循环内部。它不会将它们存储在列表或 JSON 中以进行任何操作。它只返回一个空列表或空 JSON。
- 第一个函数只是对 URL ('/api/getList') 的调用,效果很好。
- 第二个函数调用 Facebook 页面上的最新帖子。这会返回帖子 ID,我将它们放入列表中就可以了。
- 第三个函数是对 Facebook 的另一个调用,它使用帖子 ID 来请求所述帖子中的照片 URL。这会返回并控制台记录 URL,但我无法将它们存储到任何内容。奇怪的是,当我在最后一个函数中控制台登录“i”时,它返回“25”二十五次。 25 是帖子数量、返回的图像 URL 数量。
第一个函数被调用一次。第二个函数被调用一次。第三个函数被调用二十五次。
如果您想知道为什么我有两个 for 循环应该做同样的事情,那是因为我认为这可能已经解决了问题。我用一个循环得到了相同的结果。
const FB = require('fb')
var image_urls = []
app.get('/api/getList', (req, res1) => {
FB.api('4300000000643', { fields: 'posts' }, function (res2) {
if(!res2 || res2.error) {
console.error(!res2 ? 'error occurred' : res2.error);
return;
}
post_id = res2.posts.data.map(post => post.id)
for (var i = 0; i < post_id.length; i++) {
console.log(i)
FB.api(
"/"+post_id[i]+"/attachments",
function (res3) {
if(!res3 || res3.error) {
console.error(!res3 ? 'error occurred' : res3.error);
return;
}
// this doesn't seem to do anything
image_urls.push(res3.data[0].media.image.src)
// this logs all the URLs I want
// console.log(res3.data[0].media.image.src)
// this logs '25' twenty five times for some reason
console.log(i)
}
);
}
// this returns the array of post ids
console.log(post_id)
// this returns an empty list
console.log(image_urls)
});
});
“FB.api”来自 'NodeJS Library for Facebook'
在我从 Facebook 文档中获得的最后一个函数中调用的 FB.api("/"+post_id[i]+"/attachments",
here. 它似乎没有给出任何信息有关它到底是什么类型的功能的信息。
Facebook Node 包没有任何文档来说明如何查询我所看到的各个帖子的信息。
我来自 Python,对 Express/Node 还很陌生,这确实令人困惑,我有兴趣向您了解这里发生了什么。
最佳答案
您正在处理异步处理,因此您必须跟踪应该获得多少结果,并且只有在实际拥有所有这些结果后才执行“需要对所有图像网址执行的操作”:
const globalImageList = [];
app.get(`/api/getList`, (req, res) => {
FB.api(`4300000000643`, { fields: `posts` }, postData => {
if (!postData || postData.error) {
console.error(!postData ? `error occurred` : postData.error);
return res.status(500).write(`server error of some sort`);
}
const processList = postData.posts.data.map(post => post.id);
let resultCount = 0;
processList.forEach(post_id => {
FB.api(`/${post_id}/attachments`, imageData => {
resultCount++;
if (!imageData || imageData.error) {
return console.error(!imageData ? `error occurred` : imageData.error);
}
const url = imageData.data[0].media.image.src;
if (url) {
globalImageList.push(url);
}
// Do we have all the images we needed?
if (resultCount === processList.length) {
console.log(`Image URLs:`, globalImageList);
sendImageList(res);
}
});
});
});
});
函数 sendImageList(res) 可以执行您需要它执行的任何操作(发送纯文本、json、html、xml 等)。
还有一点需要考虑:不要浪费时间重新获取相同的数据,因此在点击 FB.api
之前,检查 globalImageList
是否已填充。如果是这样,请立即 res.write
响应(或您用来形成其余代码所依赖的格式正确的响应的任何 API)并返回。
关于javascript - 我需要在 Express 中附加这些嵌套函数的列表,但这些项目不会存储,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60127985/