javascript - Node js - How to correctly use make async network calls within a module -


so part of project working on have created module uses facebook graph api make calls , return json data. can console.log() data within method out fine , it's good.

but can not return values methods, tried use 'async' npm module. have followed examples on website, still struggling working, spent day on far , still things arn't looking clearer.

so asking is:

  • firstly need call method sets authentication_token fbgraph api before can else
  • then need call each of functions (in order) , json result each , add 1 big json result
  • finally need 1 big json result origional javascript page (even though it's in module), how invoke it?

here snippit of original module (only works console.log, can't return)

module.exports = {         /**          * pass access token fbgraph module          * , call other methods populate          */          setup: function (access_token) {              graph.setaccesstoken(access_token);          },          /**          * fetches users basic info:          * age, gender, hometown, relationship status          */         getbasicinfo: function(){             graph.get("/me/", function(err, res) {                 var result = {                     'age'       : _calculateage(res.birthday),                     'gender'    : res.gender,                     'hometown'  : res.hometown.name,                     'relationship_status' : res.relationship_status                 };                 //console.log(result);                 return result;             }, function(){ console.log("done");});         },         /**          * creates body of text string          * made of users status updates          */         getposts: function(){             graph.get("/me/feed?limit="+photo_limit, function(err, res) {                 var posts = "";                 for(var i=0;i<res.data.length;i++){                     var obj = res.data[i];                     if(obj.message!=undefined) posts += obj.message+"\n";                 }                 //console.log(posts);                 return {'posts':posts};             });         },         /**          * fetches single dimension string array of          * photos user tagged in          */         getphotos: function(){             graph.get("/me/photos?limit="+photo_limit, function(err, res) {                 var photos = [];                 for(var i=0;i<res.data.length;i++){                     var obj = res.data[i];                     photos.push(obj.source); // .source full size image, .picture thumbnail                 }                 return {'photos': photos};             });         }      } 

the rest of module continues in similar way have tried using parralel async

module.exports = {     getfacebookinfo: function (access_token) {         results = {};         setup(access_token);         async.parallel([             facebookdatarequests.getbasicinfo(),             facebookdatarequests.getposts() 

any guidence on how should structure appreciated, in advance

i'd recommend structure differently. it's not necessary make 3 calls facebook, because can info in 1 call well.

so, i'd do:

  1. call facebook graph api using field expansion
  2. format results
  3. return results

also, i'd advise use promise library q

something (untested!):

module.exports = {     getfacebookinfo: function (access_token) {          setup(access_token);          function setup(access_token) {              graph.setaccesstoken(access_token);          }          function getfbinfo() {             var deferred = q.deferred();             graph.get("/me?fields=id,name,birthday,gender,hometown,relationship_status,feed.limit(25),photos.limit(25)", function(err, res) {                 if (err) deferred.reject(err);                 deferred.resolve(res);             });             return deferred.promise         }          function handleresult(result) {             var deferred = q.deferred();              result.posts = result.feed.data             delete result.feed.data;              result.photos = result.photos.data             delete result.photos.data;              deferred.resolve(result);              return deferred.promise         }          q.fcall(getfbinfo)         .then(handleresult)         .then(function(result) {             return result;         })         .catch(function (error) {             // handle error above steps         })         .done();     } } 

in main file:

var fb = require('./path/to/file/above');  var results = fb.getfacebookinfo('access_token_sdaiofhiosdhfoso'); 

Comments

Popular posts from this blog

javascript - gulp-nodemon - nodejs restart after file change - Error: listen EADDRINUSE events.js:85 -

Fatal Python error: Py_Initialize: unable to load the file system codec. ImportError: No module named 'encodings' -

javascript - oscilloscope of speaker input stops rendering after a few seconds -