0

I'm working on a module that returns a the data retrieved from an http request using the request module. However, I'm having a problem when I want to pass the data out of the function. Take this, for example.

function getData(term) {
    var parsedData
    request.post(url, term, (err, response, body) => {
        if (!err && response.statusCode == 200) {
              parsedData = doSomethingTo(body);
        }
    });
    return parsedData;
}

This method doesn't work, since the function getData() performs asynchronously and the value is returned before the request can actually return the proper data.

function getData(term) {
    var parsedData
    request.post(url, term, (err, response, body) => {
        if (!err && response.statusCode == 200) {
              parsedData = doSomethingTo(body);
              return parsedData;
        }
    });
}

This method doesn't work either, as it will merely make the request function return the parsed data, and not the getData function.

How could I make the parent function return the data parsed from the request function?

110Percent
  • 271
  • 2
  • 5
  • request.post is asynchronous, you'll either have to pass a callback function to your getData function that is executed with the parsedData, or use a Promise – Patrick Hund Mar 05 '17 at 16:38

2 Answers2

0

use Promise like this :

function getData(term) {
    return new Promise(function(resolve){
      request.post(url, term, (err, response, body) => {
        if (!err && response.statusCode == 200) {
              var parsedData = doSomethingTo(body);
              resolve(parsedData);
        }
      });
   });
}

and you can call your function like this :

getData(term).then(function(data){
   //console.log(data);
}) 
El houcine bougarfaoui
  • 35,805
  • 9
  • 37
  • 37
0

use the bluebird promise module very fast.

var Promise = require('bluebird');
function getData(term) {
return new Promise(function(resolve,reject){


     if (!err && response.statusCode == 200) {
          var parsedData = doSomethingTo(body);
          resolve(parsedData);
    }else{
    reject(err);
    }
});

}; 

then the place you are calling the function do this;

var promise = getData(term);
promise.then(function(data){console.log(data)}).catch(function(err){console.error(err)});
Remario
  • 3,813
  • 2
  • 18
  • 25