簡體   English   中英

使用Google Spreadsheet節點模塊向Google電子表格添加一行並返回狀態

[英]Adding a row to a google spreadsheet using google-spreadsheet node module and returning the status

我能夠使用google-spreadsheet節點模塊成功將行添加到google電子表格中,如下所示:

const logToGoogleSpreadsheet = (userName, description, link) => {
  const spreadsheetId = 'my-spreadsheet-id'
  const doc = new GoogleSpreadsheet(`${spreadsheetId}`)
  const clientEmail = 'my-client-email'
  const privateKey = 'my-private-key'
  const payload = {
    client_email: clientEmail,
    private_key: privateKey
  }
  let status = ''
  doc.useServiceAccountAuth(payload, function (err) {
    doc.addRow(1, { 'Reported By': userName, 'Description': description, 'Screenshot Link': link,  'Status': 'Open' }, function(err) {
      if(err) {

        console.log(err);
        status = 'some error'
      } else {
        console.log('It worked')
        status = 'success'
      }
    }); 
  })
  return status
}

const result = logToGoogleSpreadsheet('username', 'description', 'link')
console.log(`The value of result is ${result}`) //This always shows undefined as the value

結果的值始終為'undefined' 我知道這是由於javascript的異步特性所致,並且無法修改回調函數中的任何內容,但是我無法解決此問題。 有人可以告訴我如何從logToGoogleSpreadsheet函數返回狀態的示例嗎?

謝謝

您可以這樣做:

const logToGoogleSpreadsheet = *async* (userName, description, link) => {//add async keyword
  const spreadsheetId = 'my-spreadsheet-id'
  const doc = new GoogleSpreadsheet(`${spreadsheetId}`)
  const clientEmail = 'my-client-email'
  const privateKey = 'my-private-key'
  const payload = {
    client_email: clientEmail,
    private_key: privateKey
  }
  let status = ''
  doc.useServiceAccountAuth(payload, function (err) {
    doc.addRow(1, { 'Reported By': userName, 'Description': description, 'Screenshot Link': link,  'Status': 'Open' }, function(err) {
      if(err) {

        console.log(err);
        status = 'some error'
      } else {
        console.log('It worked')
        status = 'success'
      }
    }); 
  })
  return status
}

logToGoogleSpreadsheet('username', 'description', 'link').then(res => console.log(res));

logToGoogleSpreadsheet添加async關鍵字將使其返回Promise。 現在它是一個“ thenable”,這意味着可以使用已解析的結果調用then方法,這就是您的狀態。 因此,在then通話中,我們將其記錄下來。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM