首页 > 解决方案 > 在 Express.JS 中呈现页面之前的异步请求

问题描述

我正在尝试在 express.js 中实现一个 HTTP 请求序列以用于培训目的。为了做到这一点,我使用 async/await 来等待我的请求并将它们包装在 try catch 块中。一切都按方面工作,因为我添加了一些 console.log 来检查流程。一切完成后,我想使用内置的 res.render() 函数渲染我的页面,但是在调用 res.render() [res.render 不是函数] 时会引发错误。

我可以通过 AJAX 加载数据,但这真的有必要吗?

/* Express Functions */
router
.get('/', async function (res,req,next){
    try{
        doSynchronousThings();
        const ParticipantIds = await xingRequests.getParticipantIds();
        console.log('...getParticipantIds response:');
        console.log(ParticipantIds);
        finalLog();
        const ParticipantData = await xingRequests.getParticipantData(ParticipantIds[0]);
        console.log('...getParticipantData response:');
        console.log(ParticipantData);
        console.log('...all done');
    }catch(err){
        console.error(err);
        next(err);
    }
    res.render('test', {
        page: {
            title:'Xing Event API',
            message: 'Happy Hacking!'
        }
    });
});

xingRequest 方法只是触发基于请求承诺的请求并返回响应对象。

标签: javascriptexpressasync-await

解决方案


推荐阅读