0

I am new to node js and I have a function where I should pass the source and destinations and then the result will be distance among the given places: here is a sample of my code :

    cartSchema.methods.getLocation = function (destinations, origins) {
  let result = {};
  try {
    distance.matrix(origins, destinations, function (err, distances) {
      if (!err) result = distances;
    });
  } catch (e) {
    res.status(500).json({ message: e.message });
  }

  console.log(result);
  return result;
};

as you can see here I want to return the distances where I have passed its value to the result but it still not return undefined.

Thanks in advance

Abdulmalek
  • 105
  • 1
  • 10
  • Does this answer your question? [How to return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-asynchronous-call) – ponury-kostek Jun 17 '21 at 18:19
  • Thanks for responding, this is an async call but I do not know why the above function does not return the result – Abdulmalek Jun 17 '21 at 18:23

2 Answers2

2

USE PROMISE

The Promise object represents the eventual completion (or failure) of an asynchronous operation and its resulting value.

in you case you need something like this:


    cartSchema.methods.getLocation = function (destinations, origins) {
      return new Promise((resolve) => {
        try {
          distance.matrix(origins, destinations, function (err, distances) {
            if (!err) result = distances;
            ...
            resolve(result);
          });
        } catch (e) {
          res.status(500).json({ message: e.message });
        }
      }
    };

    /// access to the result
    cartSchema.methods.getLocation().then(result=>{console.log(result);})

Taur
  • 514
  • 3
  • 8
0

I see, you can solve this with promises or callback functions. Here is a callback example. It cannot return the result without promises. Instead, give it a function to call (successCallback) when it gets the result.

cartSchema.methods.getLocation = function (destinations, origins, successCallback, errorCallback) {
  try {
    distance.matrix(origins, destinations, function (err, distances) {
      if (!err) successCallback(distances)
      else {
        errorCallback(err);
      }
    });
  } catch (e) {
   errorCallback(e);
  }
};
cartSchema.methods.getLocation({}, {}, function(distances){
 //do something with distances here
}, console.err)
tanner burton
  • 1,049
  • 13
  • 14