Dismiss
Announcing Stack Overflow Documentation

We started with Q&A. Technical documentation is next, and we need your help.

Whether you're a beginner or an experienced developer, you can contribute.

Sign up and start helping → Learn more about Documentation →

Basically I have a method fetching values from an API and works, but inside async.parallel the results listed are all undefined.

Here's the method:

function getNumberOfSharesFromFacebookApi(url ,callback) {

  request(facebookApiUrl + url + '&format=json', function (error, response, body) {
    let res = 0;

    if (!error && response.statusCode == 200) {
      try {
        res = JSON.parse(body)[0]['total_count'];
      } catch(err) { }
    }
    callback(res);
  });
}

Here's the async call:

async.parallel ([
  callback => {
    getNumberOfSharesFromFacebookApi(urlsToTest[0], callback);
  },
  callback => {
    getNumberOfSharesFromFacebookApi(urlsToTest[1], callback);
  },
  callback => {
    getNumberOfSharesFromFacebookApi(urlsToTest[2], callback);
  },
  callback => {
    getNumberOfSharesFromFacebookApi(urlsToTest[3], callback);
  }
],
(err, results) => { 
  console.log(results);
});
share|improve this question
    
Async.js expects you to use the node callback convention, wherein the first argument signifies an error. Your getNumberOfSharesFromFacebookApi function doesn't do that. – Bergi Jun 28 at 17:23

on your request function, place your response as the 2nd argument of the callback. request uses node style callbacks wherein the 1st argument is an error.

 function getNumberOfSharesFromFacebookApi(url ,callback) {
    request(facebookApiUrl + url + '&format=json', function (error, response, body) {
      if(error) return callback(error); //callback on error
      let res = 0;

      if (!error && response.statusCode == 200) {
        try {
          res = JSON.parse(body)[0]['total_count'];
        } catch(err) { }
      }
      callback(null, res);
    });
  }
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.