1

I'm trying to recover the value of a function but it doesn't returns anything

This is the function (Request is an async function that makes a get petition):

var getVolumesOKCoin = function(pair){
  request('https://www.okcoin.com/api/v1/depth.do?symbol=' + pair, function (error, response, body) {
    return body;
  });
}

And this is how I recover the value

var  retObj = getVolumesOKCoin(pair);

The value of retObj is undefined.

What is the best way to recover the value?

Thanks for your help.

Enrique Alcazar
  • 381
  • 7
  • 21

2 Answers2

3

First things first: your function is called getVolumesOKCoin and not getVolumes.

But still your function won't return anything, because you are calling an async function that needs some time to receive data before returning it. See this question here about how asynchronous calls work.

One solution would be to wrap your function body inside a so called Promise and resolve it as soon as data was received.

var getVolumesOKCoin = function(pair) {
  return new Promise( ( resolve, reject ) => {
    request('https://www.okcoin.com/api/v1/depth.do?symbol=' + pair, (error, response, body) => {
      resolve( body );
    } );
  } );
}

getVolumesOKCoin()
  .then( ( body ) => {
    console.log( body );
  } )
  .catch( ( err ) => {
    console.error( 'Error!' );
  } );

Also make sure, request is defined.

lumio
  • 7,428
  • 4
  • 40
  • 56
0

Simple add return to the request.

var getVolumesOKCoin = function(pair){
  return request('https://www.okcoin.com/api/v1/depth.do?symbol=' + pair, function (error, response, body) {
    return body;
  });
}
underscore
  • 6,495
  • 6
  • 39
  • 78