How to work with data from a Promise

58 views Asked by At

I'm new to JavaScript and am currently unable to wrap my head around Promise and how to retrieve data from them. I am using Express and Objection and have a route where I'd like to pull some data from the database und pass it to express' res.render() function.

So I did a lot of searching and found few examples but I was not able to incorporate what I found into my app.

//search.js ... boilerplate stripped
router.all('/', function (req, res, next)
{
    Equipment.query().select().then(equip =>
                           {
                               return equip;
                           });
    res.render('search/search', {title: 'Search', data: {formdata: req.body, equipment: "equipmentdata here"}});
});
module.exports = router;

Could anybody point me in the right direction? I did understand that I can't get data from a Promise like I would get from a function call. Also I can't imagine that it is not possible to use this ORM-Tool (which seems to only work with Promises) and retrieve data from the database and output it to the user. (Yes I had a look at the Objection Example but this is not using views.)

1

There are 1 answers

0
chilly On BEST ANSWER

I figured something out. Might not be the best solution but I decided to share what I came up with. Maybe someone runs into the same problem.

First: I define the route and a set of functions to handle specific parts:

router.post('/', getRealEstateEquipment, getRealEstate, saveSearch, renderSearchresultPage);

Second: As every function I use the provided function params (which every of my functions has) to store the retrieved data in the request instance.

Real_Estate_Equipment // Objection model instance
    .query()
    .then(data =>
    {
        // get the data and store it
        req.real_estate_equipment = data;
        return next();
    })
    .catch(err =>
    {
        return next(err);
    });

One might argue if it is better to store it in the response or request instance.

Third: The last function for the route handles what the user get (redirect / render).

function renderSearchresultPage(req, res, next)
{
    res.render('search/search', {
        data: {
            equipments: req.real_estate_equipment,
            result: req.real_estate,
            formdata: req.body
        },
        title: 'Searchresults'
    });
}

So first I handle (in multiple small steps) the required actions to retrieve data and store some information. On the last step I can do some modifications to the data, put it into a structure (easier handling in the template engine and consistent for every route I have).

For me this was the solution which simply worked best.