0

I want to access the return value of exported functions but am not able to access the value. Always got undefined output. Below is my coding, In the server.js file I have called my index.js function with the callback function. In index. js file I have defined function body.

server.js file

router.post('/node/express/upload', upload.single("file"), (req, res) => {
  pool.connect((err, client, release) => {
    // const companyname = req.body.companyname;
    // const ecomplatform = req.body.ecomplatform;
    const {companyname,ecomplatform,voucher} = req.body;
    const filename = req.file.filename;
    var workbook = XLSX.readFile('./public/'+filename);
    var sheet_name_list = workbook.SheetNames;
     
      pool.query(
        `SELECT xmlschema FROM company WHERE companyname = '${companyname}' AND ecomplatform = '${ecomplatform}' AND vouchertype = '${voucher}'`,
        (err,result) => {
          try {
            if (err) {
              logger.error(err);
              throw err;
            }
            const xmlschema = result.rows
            var final;
            final =  abc.addInvoice(workbook,sheet_name_list,xmlschema,function(response) {
              console.log('hello')
              final = response
              return response
            })
            
            console.log(final)
            res.status(201).send({msg:'Ok'})
            
          } catch (error) {
           
            next(error);
          }
        },
      );

  });
});

index.js file

function addInvoice(workbook,sheet_name_list,xmlschema,callback) {
  
  //count number of rows in xlsx file
  let count = [];
  for (var sheetIndex = 0; sheetIndex < sheet_name_list.length; sheetIndex++) {
    var worksheet = workbook.Sheets[sheet_name_list[sheetIndex]];
    var range = XLSX.utils.decode_range(worksheet["!ref"]);
    var num_rows = range.e.r - range.s.r + 1;
    count.push({
      data_count: num_rows,
    });
  }

  sheet_name_list.forEach(function (y) {
    var worksheet = workbook.Sheets[y];
    var headers = {};
    var data = [];
    for (z in worksheet) {
      if (z[0] === "!") continue;

      var tt = 0;
      for (var i = 0; i < z.length; i++) {
        if (!isNaN(z[i])) {
          tt = i;
          break;
        }
      }
      var col = z.substring(0, tt);
      var row = parseInt(z.substring(tt));
      var value = worksheet[z].v;

      //store header names
      if (row == 1 && value) {
        headers[col] = value;
        continue;
      }

      if (!data[row]) data[row] = {};
      data[row][headers[col]] = value;
    }

    var voucher,order_id,date,orderstate,seller_gst,product_id,quantity,voucher_no,product_name;
    let IGST, CGST, amount, famount, agst_ref, freturnamount, eventsubtype;

    let schema = xmlschema.map((item) => item.xmlschema)
 
    voucher = data.map((item) => item.Event_Type);
    
    order_id = data.map((item) => item.Order_ID);

    date = data.map((item) => item.Order_Date);

    orderstate = data.map((item) => item.Customer_Billing_State);

    seller_gst = data.map((item) => item.Seller_GSTIN);

    product_id = data.map((item) => item.SKU);

    quantity = data.map((item) => item.Item_Quantity);

    voucher_no = data.map((item) => item.Buyer_Invoice_ID);

    product_name = data.map((item) => item.Product_Title);

    IGST = data.map((item) => item.IGST_Amount);

    CGST = data.map((item) => item.CGST_Amount);

    amount = data.map((item) => item.Taxable_Value);

    famount = data.map((item) => item.Buyer_Invoice_Amount);

    agst_ref = data.map((item) => item.Order_Item_ID);

    freturnamount = data.map((item) => item.Final_Invoice_Amount);

    eventsubtype = data.map((item) => item.Event_Sub_Type);
    

    for (i = 2; i <= num_rows; i++)
    primeschema(
        voucher[i],
        date[i],
        orderstate[i],
        order_id[i],
        seller_gst[i],
        product_id[i],
        quantity[i],
        voucher_no[i],
        product_name[i],
        IGST[i],
        CGST[i],
        amount[i],
        famount[i],
        agst_ref[i],
        freturnamount[i],
        eventsubtype[i],
        schema,function(response){         
         return  callback(response)
        }
      );
  });

}


module.exports = {addInvoice};

I have used the callback function when a task gets completed and is an asynchronous equivalent for a function. please help me guys with how to access the exported function return value.

sudesh sharma
  • 55
  • 1
  • 9
  • if its asynchronous your console.log() will be called before the response is assigned to final, either put the consol.log() behind the function with a .then() or await it – Branchverse Mar 24 '22 at 07:52
  • @MaximilianDolbaum I have added all code. can you please give example of how to do it??? – sudesh sharma Mar 24 '22 at 07:58
  • Have a look at [How to return the response from an asynchronous call](https://stackoverflow.com/q/14220321/218196). Also this might help you understand how to think about callbacks: [How (not) to get a value "out of" a callback](https://felix-kling.de/blog/2019/javascript-callbacks-misconceptions.html) – Felix Kling Mar 24 '22 at 07:59

0 Answers0