我正在尝试使用Facebook Graph API以递归方式获取我的所有Facebook帖子。
对Facebook API的简单GET请求不会返回我的所有帖子。相反,它会返回分页响应。
{"data": [
{Facebook post},
{Facebook post},
{Facebook post}.
etc
],
"paging": {
"next":Url (api endpoint) to next page of results
}
}
所以,我必须递归在paging.next上发出GET请求以检索我的所有帖子。
使用同步 HTTP请求执行此操作非常简单。但我正在使用NodeJS,我一直听说我应该保持异步。因此,我将HTTP GET请求方法更改为异步。
要在我的异步HTTP GET请求上获得一些控制流,我使用 async npm模块;特别是, async.waterfall
这是我的递归函数和async.waterfall:
function getAllPosts(responseObj, masterPosts) {
masterPosts = typeof masterPosts !== 'undefined' ? masterPosts : {'data':[]};
var posts = responseObj['data'];
masterPosts['data'] = masterPosts['data'].concat(posts);
if (responseObj.hasOwnProperty('paging') && responseObj['paging'].hasOwnProperty('next')) {
var r;
async.waterfall([
function(callback){
r = httpGet(responseObj['paging']['next']);
callback(null, r);
},
function(arg1, callback){
getAllPosts(JSON.parse(arg1), masterPosts);
callback(null, 'done');
},
], function (err, result) {
//result now == 'done'
});
}
return masterPosts;
}
httpGet 函数是异步的。我试过这个,但它不起作用:(我的结果仍然是我的Facebook帖子的一半。
函数参数 responseObj 是一个JavaScript对象〜刚刚解析了分页的JSON响应
我在这里缺少什么?