0

I want to use the node-zillow module to set the value of lastSoldDate but when I go to post I get the error lastSoldDate is undefined. this is what I have so far:

 router.route('/add').post((req, res) => {
        const address = req.body.address
        const street = address.street
        const zipcode = address.zipcode
        const city = address.city
        const state = address.state

        paramaters = {
        address: address.street,
        citystatezip: address.city + ", " + address.state
        }

        zillow.get('GetDeepSearchResults', paramaters)
      .then(function(results) {
        date = results.response.results.result[0].lastSoldDate[0]
        console.log(date)
        return date;
      }).then((date) => lastSoldDate = date)

        const lastSoldPrice = req.body.lastSoldPrice

        const newProperty =  new property({
            address:{
                street,
                zipcode,
                city,
                state,
            },
            lastSoldDate,
            lastSoldPrice
        })

        newProperty.save()
            .then(() => res.json('Property added!'))
            .catch(err => res.status(400).json('Error: ' + err))
    })
itsOnly1_Jah
  • 221
  • 1
  • 3
  • 10
  • I assume `zillow.get()` is async, which means `lastSoldDate = date` runs long *after* all the other commands further down. Insert `async` before `(req, res)`, then use `const lastSoldDate = await zillow.get(...).then(...);` (you can remove the 2nd `then()`, it does nothing) –  Dec 22 '19 at 22:49
  • the code starting at `const lastSoldPrice = req.body.lastSoldPrice` needs to be *inside* the `.then` - because that's how asynchrony works – Jaromanda X Dec 22 '19 at 22:50
  • Put that code that needs to use the data inside that callback, instead of `lastSoldDate = date`. – Bergi Dec 22 '19 at 22:58
  • Also you should declare your `paramaters`, `date` and `lastSoldDate` variables with `const`, otherwise they become globals – Bergi Dec 22 '19 at 22:59
  • @ChrisG That worked! I cant believe it was that simple, thanks a lot. – itsOnly1_Jah Dec 22 '19 at 23:09

0 Answers0