beforeRender() is skipping over code?



  • Hi I am requesting some data via my api but for some reason my beforeRender() function isn't running that piece of code and i'm not sure why this is the case.

    async function beforeRender(req, res) {
        require('request')({
            headers: {
                'Authorization': 'Bearer code'
            }, 
            url: 'url',
            json:true
        },
        function(error, response, body) {
            require('request')({
                headers: {
                    'Authorization': 'Bearer ' + body.JWT
                }, 
                url: 'url',
                json:true
            },
            function(error, response, data) {
                console.log('hello');
                console.log(data);
            });
        });
    }
    

    The console.log('hello') isn't logging anything and neither is the data. This is my first time using JS like this I am a PHP developer so this is all new to me, I know the basics when doing frontend stuff so hopefully it is just a silly mistake.

    One thing I will mention is if i specify done inside the parameters of beforeRender() and then add done(); after my console logs it works.

    The reason I don't want to do this is because I will be placing

    const result = await jsreport.render({ 
        template: { 
            shortid: 'H1xtsYmyWI'
        },
        data: data
    });
    console.log(result.content);
    

    where the console logs have been placed and I can't use await jsreport.render inside of a function with isn't async. The await needs to be there otherwise result.content returns undefined.

    Thanks for any help! Sorry if this is a really stupid question.



  • I recommend reading some articles about "promises, async/await and callbacks" in javascript.

    In your case, you better use axios module instead of request. Axios is based on promises/async as well as jsreport.render, so you don't have to think how to mix both together. It is, of course, possible, but you save some brain cpu cycles to figure it out.

    It could look like this

    const axios = require('axios')
    const jsreport = require('jsreport-proxy')
    
    async function beforeRender(req, res) {
      const response = await axios.get({ some params })
      const jsreportRes = await jsreport.render({ some params })
      // do whatever you need
    }
    

    If you need to use another lib that doesn't support promises, you better read some articles and get the knowledge about how to use them with promises.



  • @jan_blaha Brilliant thanks I will go and have a look into that, thank you for all the help you have been giving me! :)



  • 14 minutes later everything is working perfectly! only wasted 5 hours trying to figure it out myself... ahaha. THANK YOU


Log in to reply
 

Looks like your connection to jsreport forum was lost, please wait while we try to reconnect.