【问题标题】:reading google spreadsheet data using node js not working..?使用节点 js 读取谷歌电子表格数据不起作用..?
【发布时间】:2020-01-15 13:28:52
【问题描述】:

我正在使用邮递员调用 api。我正在尝试使用节点 js 读取谷歌电子表格行。响应正在控制台上打印,但没有返回给邮递员。

index.js 文件

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

  }
  res.send(response);
});

电子表格.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;
};

如何等待 getRecord 函数返回响应

【问题讨论】:

标签: javascript node.js google-sheets-api


【解决方案1】:

res.send(response); 移动到try 块内并阅读有关how to return response from an async call 的信息。

return jsonObj 也应该在 try 块内

【讨论】:

  • catch 块内的打印错误。你看到任何错误吗?
【解决方案2】:

我使用 promise call 现在它可以工作了。

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
};

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-20
    相关资源
    最近更新 更多