简体   繁体   中英

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

I am able to successfully add a row to a google spreadsheet using the google-spreadsheet node module as follows:

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

The value of result always is 'undefined' . I know this is due to the asynchronous nature of javascript and being unable to modify anything in a callback function, but im not able to fix this issue. Can someone please show me an example of how i can return the status from the logToGoogleSpreadsheet function ?

Thank You

you could do this:

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

adding the async keyword to logToGoogleSpreadsheet will make it return a Promise. Now it is a 'thenable' meaning the then method can be called with the resolved result, which here is your status. So in the then call we log it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM