0

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' })
};
Mat Sz
  • 2,524
  • 1
  • 10
  • 23
Marc Vila
  • 5
  • 1

1 Answers1

0

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'
  })
};

Phix
  • 9,364
  • 4
  • 35
  • 62
  • Hi, Thank you very much for your help, your code has served me perfectly. That said I thought async await, replaced the concept of promises but I see no. I will continue studying but this problem disappeared! – Marc Vila Feb 11 '20 at 16:19