Search code examples
node.jsasync-awaitgoogle-distancematrix-api

Google Distance does not work with async await


I am trying to use google-distance package of node to calculate the distance between two cities, and once this distance is stored in a mongodb database, next to other fields from a form. The problem I find is that I don't know how to return the value of the function to store it in the database and it always returns an undefined. Anyone know where I can fail?

removalsCtrl.createRemoval = async (req, res) => {
    const { name, email, origin, destination } = req.body;

    let kilometers = await distance.get({ origin, destination }, function (err, data) {
        if (err) return console.log(err);
        return data.distanceValue;

    })

    const newRemoval = await new Removal({
        name,
        email,
        origin,
        destination,
        kilometers
    })

    await newRemoval.save();
    res.json({ message: 'Removal Saved' })
};

Solution

  • distance.get doesn't return a Promise, so you'll either need to wrap it in a function that does, or move the rest of your code inside the callback, i.e.

    removalsCtrl.createRemoval = async (req, res) => {
      const {
        name,
        email,
        origin,
        destination
      } = req.body;
    
      const getKilometers = (origin, destination) => {
        return new Promise((resolve, reject) => {
          distance.get({ origin, destination }, function(err, data) {
            return err ? reject(err) : resolve(data);
          })
        })
      }
    
      // Be sure to handle failures with this, or however you decide to do it
      const kilometers = await getKilometers(origin, destination);
    
      const newRemoval = await new Removal({
        name,
        email,
        origin,
        destination,
        kilometers
      })
    
      await newRemoval.save();
      res.json({
        message: 'Removal Saved'
      })
    };