Im using a library for working with google spreadsheets And to work with multiple sheets I've made a singleton class that contains document object, so that all other classes can get sheet from this class.
Singleton Class
export class Singleton {
private static document: GoogleSpreadsheet;
private static async loadDocument(): Promise<void> {
Singleton.document = new GoogleSpreadsheet(config.spreadsheetID);
await Singleton.document.useServiceAccountAuth(await import('./api.json'));
await Singleton.document.loadInfo();
}
public static async getSheet(sheetIndex: number): Promise<GoogleSpreadsheetWorksheet> {
if (!Singleton.document) {
await Singleton.loadDocument();
}
const sheet = Singleton.document.sheetsByIndex[sheetIndex];
await sheet.loadCells('A1:H100');
return sheet;
}
}
And here how I use it
async function fillInfoInSheet(columnIndex: number): Promise<void> {
const sheet = await Singleton.getSheet(8);
const cell = sheet.getCell(0, columnIndex);
cell.value = 'Changed';
await sheet.saveUpdatedCells();
}
for (let i = 0; i < 3; i++) {
fillInfoInSheet(i);
}
If i debug the code I can seee that a problem happeneds in Class file on line 6
await Singleton.document.useServiceAccountAuth(await import('./api.json'));
After skiping this line, debugger goes back to line 11 with methods parameter 'sheetIndex' 1 instead of 0
if (!Singleton.document) {
And then it goes to line 15 and throwing exception because 'loadInfo()' method hasn't been executed.
So, my question is, how to make method loadDocument execute only once, without awaiting for 'fillInfoInSheet'?
Aucun commentaire:
Enregistrer un commentaire