[英]Response object is not defined when passed in a function
I am using Facebook Graph NodeJS API
to fetch user_posts
. 我正在使用Facebook Graph NodeJS API
user_posts
Facebook Graph NodeJS API
来获取user_posts
。 The response has pagination and therefore I need to loop over the response to fetch all the posts. 响应具有分页,因此我需要遍历响应以获取所有帖子。 I am using following route to fetch facebook posts and I am looping over pagination using get_user_statuses
function: 我正在使用以下路线来获取Facebook帖子,并且正在使用get_user_statuses
函数遍历分页:
var posts = "";
function get_user_statuses(response_posts, res) {
var link_regex = /https?:\/\/(?:www\.|(?!www))[^\s\.]+\.[^\s]{2,}|www\.[^\s]+\.[^\s]{2,}/g;
var isNextPageAvailable = true;
if ("paging" in response_posts) {
var nextPage = response_posts.paging.next;
isNextPageAvailable = true;
} else {
isNextPageAvailable = false;
}
for (var i = 0; i < response_posts.data.length; i++) {
var post = response_posts.data[i].message + " ";
if ("message" in response_posts.data[i]) {
posts += post.replace(link_regex, "");
}
}
if (nextPage !== undefined) {
request(nextPage, function (error, response, body) {
if (!error && response.statusCode === 200) {
get_user_statuses(JSON.parse(body));
} else {
console.log(error);
}
});
}
if (!isNextPageAvailable){
//Sending posts to facebook Modal
console.log(posts);
res.send(JSON.stringify({posts: posts})); //res is not defined here
}
}
router.post('/fbData', function (req, response, next) {
FB.setAccessToken(req.body.access_token);
FB.api('/me?fields=posts&posts.limit=1000', function (res) {
if (!res || res.error) {
if (!res) {
response.send(JSON.stringify({error: 'An error occurred. Please try again.'}))
}
response.send(JSON.stringify({error: response.error}));
return;
}
get_user_statuses(res.posts, response); //Passing response object here
});
});
The issue is that response
object passed from express route
is not defined in get_user_statuses
function. 问题是从快速route
传递的response
对象未在get_user_statuses
函数中定义。 Now I have two question: 现在我有两个问题:
I solved my problem. 我解决了我的问题。 I needed to create a function with a callback. 我需要创建一个带有回调的函数。 In case anyone else is stuck at this kind of issue, this post helped me resolve it: 万一其他人陷入这种问题,这篇文章可以帮助我解决:
[ How to recurse asynchronously over API callbacks in node.js? [ 如何通过node.js中的API回调异步递归?
res
is not defined because you forgot to pass it in internal call. 未定义res
因为您忘记在内部调用中传递它。 Change get_user_statuses(JSON.parse(body));
更改get_user_statuses(JSON.parse(body));
to get_user_statuses(JSON.parse(body), res);
到get_user_statuses(JSON.parse(body), res);
and it should work 它应该工作
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.