0

I am using postman to call api. I am trying to read google spread sheet row using node js. Response is printing on console but its not returning to postman.

index.js file

app.post('/myapi/getClientkey',async (req, res) => {
  var response = null;
  console.log("Inside myapi");
  try {
    response = await spreadsheet.getRecord();
  } catch(err){

  }
  res.send(response);
});

spreadsheet.js

var config = require('./config.json');
var GoogleSpreadsheet = require('google-spreadsheet');
var creds = {
  client_email: config.client_email,
  private_key: config.private_key
}
var doc = new GoogleSpreadsheet(config.GOOGLE_SHEET_ID)
var sheet = null;


exports.getRecord =  async function () {

  console.log('Inside - getRecord');
  var name = null;
  var jsonObj = {};
  try {
          doc.useServiceAccountAuth(creds, async function (err) {
            // Get all of the rows from the spreadsheet.
            await doc.getRows(1, async function (err, rows) {
                if(rows != null){
                  var oneRow = rows[0];
                  name = oneRow.name;
                  console.log("name :"+name);
                  jsonObj.client_name = name.toString();
                }
              console.log(jsonObj);  
            });
          }); 
   }catch(err){
      console.log("err :"+err);
  }
  return jsonObj;
};

How to wait till response is returned from getRecord Function

Developer Desk
  • 2,294
  • 8
  • 36
  • 77
  • Check the next answer on thread [Google Drive API promise doesn't return at all when called from an AWS Lambda function (but works fine locally)](https://stackoverflow.com/a/59092228/6868879), it has mostly the same request. Let me know if it helps you. – Jeff Rush Jan 15 '20 at 15:01

2 Answers2

1

Move res.send(response); inside try block and read about how to return response from an async call.

Also return jsonObj should be inside try block

Muhammad Usman
  • 10,039
  • 22
  • 39
0

I used promise call now it working.

exports.getRecord =  async function () {

  console.log('Inside - getRecord');
  var name = null;

  return new Promise( async function(resolve,reject){
      try {
              var jsonObj = {};
              doc.useServiceAccountAuth(creds, async function (err) {
                // Get all of the rows from the spreadsheet.
                await doc.getRows(1, async function (err, rows) {
                    if(rows != null){
                      var oneRow = rows[0];
                      name = oneRow.name;
                      console.log("name :"+name);
                      jsonObj.client_name = name.toString();
                    }
                  console.log(jsonObj);  
                  resolve(jsonObj);
                });
              }); 
       }catch(err){
          console.log("err :"+err);
          reject();
      }
    }); // end of promise
};
Developer Desk
  • 2,294
  • 8
  • 36
  • 77