Error using async-await



  • Hi,
    I am trying to use async-await in the script to get my data. This is with version 2.1.0 and I get the error

    Error: Error while executing user script. await is only valid in async function
        at VMScript.compile (C:\ifolder\iroot\jsReport2\node_modules\jsreport-core\lib\render\safeSandbox.js:162:26)
        at VM.run (C:\ifolder\iroot\jsReport2\node_modules\vm2\lib\main.js:212:52)
        at run (C:\ifolder\iroot\jsReport2\node_modules\jsreport-core\lib\render\safeSandbox.js:171:19)
    

    Am I missing some configuration to enable async-await. This is my function.

    async function getRptData(req, bidId, done){
        getReq.get({url:`${Url}`, json:true},
        (err, response, body) => {
            if (err) done(err);         
            req.data.contract = body[0] || {};        
            req.data.contractTo = await getPrimeContractor(bidId);
            done();
        });
    }
    

    Thank you for helping me.


  • administrators

    hi!, there is no configuration to enable async-await, it just depends on your nodejs version and nothing specifically inside jsreport.

    according to javascript semantics await can be used only inside a function that is defined as async too. in your case it is not working because you are using await inside a function that is not async (that request callback (err, response, body) => {}). it can be a little confusing but remember that in order to use await you need to make sure that the function that contains the instruction is async too.

    a good solution can be this:

    async function getRptData(req, bidId, done){
       const doRequest = () => {
          return new Promise((resolve, reject) => {
             getReq.get({url:`${Url}`, json:true}, (err, response, body) => {  
                if (err) { return reject(err) }
                resolve({ response, body })
             })
          })
       }
    
       const { body } = await doRequest()
       req.data.contract = body[0] || {};        
       req.data.contractTo = await getPrimeContractor(bidId);
       done();
    }
    


  • Thank you. much appreciated.


Log in to reply
 

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