Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading