Home > front end >  Why does declaring a variable using googleSheets.spreadsheets.values.get only work as an IIFE?
Why does declaring a variable using googleSheets.spreadsheets.values.get only work as an IIFE?

Time:04-30

Context: this is not a request for help, I found the solution, I just want to understand why.

Working code:

  var username_result = (await googleSheets.spreadsheets.values.get({
    auth,
    spreadsheetId,
    range: "users!A"   selrow,
  })).data;

This returns the expected object, and I can log it to console to view its contents.

If I remove the outer set of parentheses, i.e. making this not an IIFE, username_result is undefined.

I read through this question and it seems to suggest that googleSheets.spreadsheets.values.get({}).data would otherwise not return any value if not wrapped as an IIFE. I looked at the documentation for this function and it explicitly states that it returns a range of values.

I hate implementing code that I don't fully understand. Why does this need to be an IIFE to work?

CodePudding user response:

That's not an IIFE. It's just the grouping operator (parentheses).

You need it because await has lower precedence than property access. So with it, you're awaiting what you get from get(/*...*) and then reading the data property from the result of the await. Without it, you're accessing a data property on the promise get(/*...*/) returns (it doesn't have one) and using await on the resulting value (undefined).

So you need the grouping operator, or you could use destructuring:

var {data: username_result} = await googleSheets.spreadsheets.values.get({
    auth,
    spreadsheetId,
    range: "users!A"   selrow,
});

...or just two statements:

const result = await googleSheets.spreadsheets.values.get({
    auth,
    spreadsheetId,
    range: "users!A"   selrow,
});
var username_result = result.data;
  • Related