0

I can see the data in the log but I can't get it out of the function.

var distance = require('google-distance');
distance.get(
{
    index: 1,
    origin: '37.772886,-122.423771',
    destination: '37.871601,-122.269104'
},
function(err, data) {
    if (err) return console.log(err);
    console.log(data);
    return data;
});

I can see the data in the console so I tried this:

var distance = require('google-distance');
var output = distance.get(
{
    index: 1,
    origin: '37.772886,-122.423771',
    destination: '37.871601,-122.269104'
},
function(err, data) {
    if (err) return console.log(err);
    return data;
});
console.log(output);

This logs 'undefined'

I suspect that I need to use a promise or something. Can someone give me an example?

UPDATE: Here is how I tried to implement a promise.

var promise = require('promise');
var tideDistance = {};
var p = new promise(function(resolve, reject) {

    distance.get(
    {
      index: 1,
      origin: '37.772886,-122.423771',
      destination: '37.871601,-122.269104'
    },
    function(err, data) {
      if (err) reject(err);
      resolve(data);
      return data;
    });
});

p.then(function(result) {
    tideDistance = result;
    return result;
}).catch(function(err) {
    console.log(err);
});
console.log(tideDistance);

This logs {}

KahunaCoder
  • 615
  • 7
  • 14
  • Possible duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Kevin B Aug 11 '17 at 18:07

2 Answers2

0

Use callback function

var distance = require('google-distance');
function callbackFunction(result) {
   console.log(result); // use the result for manipulation
}
distance.get(
{
   index: 1,
   origin: '37.772886,-122.423771',
   destination: '37.871601,-122.269104'
},
function(err, data) {
   if (err) return console.log(err);
   callbackFunction(data);
});
Bharathvaj Ganesan
  • 3,054
  • 1
  • 18
  • 32
-1
var distance = require('google-distance');
distance.get({
       index: 1, 
       origin: '37.772886,-122.423771', 
       destination: '37.871601,-122.269104'
      }, function(err, data) { 
         if (err) 
             return console.log(err);     
         callback(data);
      }); 
function callback(result){
         console.log(result);
} 
mehta-rohan
  • 1,373
  • 1
  • 14
  • 19