【问题标题】:How to work with data from a Promise如何处理来自 Promise 的数据
【发布时间】:2017-11-17 20:10:24
【问题描述】:

我是 JavaScript 新手,目前无法理解 Promise 以及如何从中检索数据。 我正在使用 Express 和 Objection 并且有一条路线,我想从数据库中提取一些数据并将其传递给 express 的 res.render() 函数。

所以我做了很多搜索,发现了几个例子,但我无法将我发现的内容整合到我的应用中。

//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;

谁能指出我正确的方向? 我确实明白,我无法像从函数调用中那样从 Promise 中获取数据。我也无法想象不可能使用这个 ORM 工具(它似乎只适用于 Promises)并从数据库中检索数据并将其输出给用户。 (是的,我查看了Objection Example,但这没有使用视图。)

【问题讨论】:

    标签: express-4 objection.js


    【解决方案1】:

    我想通了。 可能不是最好的解决方案,但我决定分享我的想法。也许有人遇到了同样的问题。

    首先: 我定义了路由和一组函数来处理特定的部分:

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

    第二: 作为每个函数,我使用提供的函数参数(我的每个函数都有)将检索到的数据存储在请求实例中。

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

    人们可能会争论是否将其存储在响应或请求实例中更好。

    第三: 路由的最后一个函数处理用户获取的内容(重定向/渲染)。

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

    首先我处理(在多个小步骤中)检索数据和存储一些信息所需的操作。 在最后一步,我可以对数据进行一些修改,将其放入一个结构中(在模板引擎中更容易处理,并且对于我拥有的每条路线都是一致的)。

    对我来说,这是最有效的解决方案。

    【讨论】:

      猜你喜欢
      • 2018-04-10
      • 2021-12-05
      • 2021-11-10
      • 2015-10-09
      • 1970-01-01
      • 2018-09-11
      • 1970-01-01
      • 2023-04-07
      • 1970-01-01
      相关资源
      最近更新 更多