javascript - 在类javascript类构造函数中使用异步调用

标签 javascript class javascript-objects

我试图在 Javascript 中创建一个类,基本上是为了完成所有谷歌表格功能。在编写任何函数之前,我在构造函数中调用了身份验证 API,但在调用实际函数之前身份验证尚未完成。这是类文件中的代码,

const { google } = require("googleapis")
const authentication = require("./authentication");

class Sheets {
    constructor() {
        this.test = 'stackoverflow';
        authentication.authenticate().then((auth)=>{
            this.auth = auth;
        });
    }

    async writeToSheet(spreadsheetId, range, data) {
        if(typeof spreadsheetId != "undefined") {
            console.log(this.test)
            console.log('Got the spreadsheetId:' + spreadsheetId)
            console.log('Got the auth:' + this.auth)
            return;    
        }

        var sheets = google.sheets('v4');
        await sheets.spreadsheets.values.update({
            auth: this.auth,
            spreadsheetId: spreadsheetId,
            range: range, //Change Sheet1 if your worksheet's name is something else
            valueInputOption: "USER_ENTERED",
            resource: {
                values: data
            }
        }, (err, response) => {
            if (err) {
            console.log('The API returned an error: ' + err);
            return;
            } else {
                console.log("Data updated to the sheet successfully!");
            }
        });
    } 
}

module.exports = Sheets;

这就是我调用函数的方式,

let sheets = await new Sheets();
sheets.writeToSheet(spreadSheetId, range, data);

当我像上面那样调用 writeToSheet 函数时,它总是像这样将 auth 打印为未定义,

stackoverflow
Got the spreadsheetId:9ijWvEeWG7Oybv_TJi5AMkjl18dFHMFcBfSfkEG24-p7
Got the auth:undefined

那么,如何在调用类中的任何其他函数之前调用 authenticate 函数并同步设置 this.auth 呢?对此的任何帮助将不胜感激。

最佳答案

我认为您只需要创建一个额外的工作流类型函数来处理身份验证部分,然后将其传递给您为 writeToSheet 所拥有的逻辑;像这样:

const { google } = require("googleapis")
const authentication = require("./authentication");

class Sheets {
    async authenticate() {
        const auth = await authentication.authenticate();
        this.auth = auth;
    }

    async writeToSheet(spreadsheetId, range, data) {
        await this.authenticate();
        await _writeToSheet(spreadsheetId, range, data);
    } 

    async _writeToSheet(spreadsheetId, range, data){
        if(typeof spreadsheetId != "undefined") {
            console.log('Got the spreadsheetId:' + spreadsheetId)
            console.log('Got the auth:' + this.auth)
            return;    
        }

        var sheets = google.sheets('v4');
        await sheets.spreadsheets.values.update({
            auth: this.auth,
            spreadsheetId: spreadsheetId,
            range: range, //Change Sheet1 if your worksheet's name is something else
            valueInputOption: "USER_ENTERED",
            resource: {
                values: data
            }
        }, (err, response) => {
            if (err) {
            console.log('The API returned an error: ' + err);
            return;
            } else {
                console.log("Data updated to the sheet successfully!");
            }
        });
    }
}

module.exports = Sheets;

这会稍微改变您对该函数的使用,如下所示:

let sheets = new Sheets();
await sheets.writeToSheet(spreadSheetId, range, data);

您可以将其中的一些添加到 构造函数 中,但请注意,您正在存储一个先前已通过身份验证的类实例。如果您存储实例并尝试稍后使用现已过期的身份验证 token 重用它,则可能会出现问题。

关于javascript - 在类javascript类构造函数中使用异步调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57301325/

相关文章:

javascript - 让事件监听器影响堆栈中的多个项目

java - 嵌套类

javascript - 将数组转换为嵌套对象 javascript

javascript - 未压缩的 SoundCloud SDK

javascript - typescript :不可分配给类型错误

javascript - 嵌入式谷歌地图 : stop the callout from automatically appearing?

c++ - 我可以在 C++ 中将类作为对象处理吗

c++ - 在另一个类 C++ 中用作成员的类的 header 包含问题

javascript - 查找不工作的回调-Javascript

Javascript 通用 For 循环