[英]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: 我能够使用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
The value of result always is 'undefined' . 结果的值始终为'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. 我知道这是由于javascript的异步特性所致,并且无法修改回调函数中的任何内容,但是我无法解决此问题。 Can someone please show me an example of how i can return the status from the logToGoogleSpreadsheet function ? 有人可以告诉我如何从logToGoogleSpreadsheet函数返回状态的示例吗?
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. 向logToGoogleSpreadsheet
添加async
关键字将使其返回Promise。 Now it is a 'thenable' meaning the then
method can be called with the resolved result, which here is your status. 现在它是一个“ thenable”,这意味着可以使用已解析的结果调用then
方法,这就是您的状态。 So in the then
call we log it. 因此,在then
通话中,我们将其记录下来。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.