jmona789 jmona789 - 20 days ago 5
CoffeeScript Question

How to return new json from a function within a promise

I have a mongoose query that finds a bunch of venues and then does a google query to find driving distances to those venues. that google function is inside a promise and in the .then I have to do

res.json venues.emitted.fulfill[0]
or else the json comes out wrapped with

"emitter": {
"domain": null,
"_events": {
"reject": [
null,
null
]
},
"_eventsCount": 2
},
"emitted": {
"fulfill": [
[...
]
]

]
},
"ended": true
}


Is there any way to avoid returning all that from the promise so I can just do res.json or is this the best way to go about this?

Here's the relevant code(coffeescript):

Venue.find {}
.lean()
.then (dbResponse) ->
venues = dbResponse
if req.param('hotelId')
hotelId = req.param('hotelId')
distancePromise = ()->
venues = findDistances(hotelId, venues, req)
Promise.resolve distancePromise()
.then ()->
res.json venues.emitted.fulfill[0]
else
res.json venues
.catch (err) ->
res.status(400).send(err)

Answer

When you call the function that returns you a promise, you should get the value that the promise is returning you and then just send that value.

Venue.find {}
  .lean()
  .then (dbResponse) ->
    venues = dbResponse
    if req.param('hotelId')
      hotelId = req.param('hotelId')          
      findDistances(hotelId, venues, req)
      .then (result)->
        res.json result
      .catch (error) ->
        res.status(404).send(err)
    else
      res.json venues
  .catch (err) ->
    res.status(400).send(err)
Comments