0

我正在使用“请求”模块从 facebook API 获取 JSON 对象:

exports.userInfo = function (userID, accessToken){
request.get({url: facebookAPI.ME + accessToken, json: true}, function(error, response, user){
    if (error) {
        console.log(error);
    } else {
        if (typeof(user) !== 'undefined'){
            return User;
        }

    }
});

};

但是,如果我从外部调用此爬虫,则不会返回有效的 JSON 对象。

var crawler = require('./helper/crawler');
console.log(crawler.userInfo(userID, accessToken)); 

当请求返回有效的 JSON 对象并将该有效的 JSON 对象返回给 userInfo 函数时,我该如何做到这一点?

谢谢你。

4

1 回答 1

0

As request is asynchron and triggers a callback, you can't use return in it. You have to pass a callback to crawler.userInfo, like this:

exports.userInfo = function (userID, accessToken, callback){
  request.get({
    url: facebookAPI.ME + accessToken,
    json: true
  }, callback);
};

And then from outside

var crawler = require('./helper/crawler');
crawler.userInfo(userID, accessToken, function (error, response) {
  console.log(response);
}); 
于 2012-06-19T13:17:26.527 回答