0

Quokka Output of my code

I have created a script meant to read data from a google sheet, the function getData() returns a promise of an Array. However, when I access the data afterwards, the value of the data is a promise of a function. Why is this the case?


import dotenv from "dotenv";
import { google } from "googleapis";
import { mainModule } from "process";

dotenv.config();

const spreadsheetID = process.env.spreadsheetID;

if (process.env.NODE_ENV == "production") {
  var fs = require("fs");

  fs.writeFile("./secrets.json", process.env.SECRET, (err: any) => {
    err;
  });
}

async function getData() {
  const auth = new google.auth.GoogleAuth({
    keyFile: "secrets.json",
    scopes: "https://www.googleapis.com/auth/spreadsheets",
  });

  const client = await auth.getClient();

  const googleSheets = google.sheets({ version: "v4", auth: client });

  var getRows = await googleSheets.spreadsheets.values.get({
    auth: auth,
    spreadsheetId: spreadsheetID,
    range: "Sheet1",
  });
  console.log(getRows.data.values);
  console.log(Array.isArray(getRows.data.values))
  return getRows.data.values;
}

const data = getData();

data.then(() => {
  console.log(Array.isArray(data);
    console.log(data);
    
  var present_list = (data as any).forEach((user: any) => {
    if (user[4] == "P") {
      present_list.append(user);
    }
  });
  console.log(present_list);
});

console.log("asdasd");

Chuah Zi Yang
  • 29
  • 1
  • 4
  • Does this answer your question? [How to access the value of a promise?](https://stackoverflow.com/questions/29516390/how-to-access-the-value-of-a-promise) – Wing Sep 19 '21 at 22:04
  • `data` here is a promise, not your data itself. You need to do `data.then(yourArray => { ...})` and then use the vlaue of `yourArray`. – jfriend00 Sep 20 '21 at 06:39

1 Answers1

0

If we want to access the data from a promise, we would want to do something like this:

//...
const data = getData();

data.then((result) => {
  const present_list = result.forEach((user: any) => {
    ...
  });
});

We don't want to use the data variable, because obviously that would a promise, even inside the callback function passed to then. We would want to use the parameter of the callback, which will be have the data extracted from the promise.

Ervin Szilagyi
  • 14,274
  • 2
  • 25
  • 40