我正在尝试使用node-facebook-sdk使用Node.JS进行FB图形API调用
我想从所有用户朋友那里获取Feed数据。 FB图API只允许每批请求50个朋友,所以我正在进行一系列批量FB.api()调用。
我试图将FB.api()调用存储在一个数组中,然后使用jQuery when()来调用延迟函数。
1)我传递给.done()函数的函数提前执行。 2)console.log(feed)在.done()之后执行,据我所知不应该发生。
$ = require('jQuery');
//maximum batch size request is 50. use 2-D array to store in buckets of 50 friends each.
var numFriends = friends.data.length;
var batch = [];
var deferred = [];//array to hold all the requests
var feed_dump = [];//where we collect all the feed data
//initialize a bucket for each set of 50 friends
for (var i = 0, ii = numFriends / 50; i < ii; i++) {batch.push([]);}
//put corresponding requests in in buckets.
for (var i = 0; i < numFriends; i++) {
batch[Math.floor(i/50)].push({ method: 'get', relative_url: friends.data[i].id + '/feed?since=' + '-1 month'});//not sure if the date format will work user.last_updated
}
//make the multiquery request for each bucket
for (var i in batch) {
var bucket = batch[i];
//nested FB api call
deferred.push(FB.api('', 'post', {'batch' : bucket}, function(res){//res = array 50 friend feeds
if (!res || res.error) {
console.log(!res ? 'error occurred' : res.error); return;
}
for (var j in res) {
var feed = JSON.parse(res[j].body);
console.log(feed);
feed_dump.push(feed);//feed for each friend appeneded to dump
}
}));
}
console.log('this should show up before graph api requests are made.');
//jQuery when() function.
$.when.apply(null, deferred).done(function() {
console.log('hopefully feed_dump has been updated...');
PySocket.emit('update_user_graph',JSON.stringify(feed_dump));
});
如何正确推迟批处理FB.api()请求?此外,如果有人能想到更好的方法,请告诉我;我对async javascript没有经验。
我想我的一个更简单的问题是:如何等待多个回调函数完成?
非常感谢。