0

I am trying to do the following, unfortunately to no avail: 1. reading a spreadsheet and get it as a parsed object. 2. use the parsed object to look for a specific value in it. e.g an email.

The spreadsheet serves as a database and the motivation is to determine whether a given email exists there or not.

Apparently, I have misunderstood the use of asynchronous methods as I can't grasp how to return the.

The calling method:

helpers.read('the-spreadsheet-id', 'Sheet1!A:Z');

The reading method @ helpers/sheets.js:

    exports.read = (spreadsheetId, range) => {
  const sheets = google.sheets({ version: 'v4', auth: oAuth2Client });

  return sheets.spreadsheets.values.get({
    spreadsheetId,
    range,
  })
    .then(_.property('data.values'));
};

what should I do in order to get a json object or similarly parsed data object to keep on working with at the calling method?

Thanks in advance.

2
  • what does helpers.read return? Are you getting the write data object back? Where are you stuck specifically? Commented Jul 29, 2019 at 21:25
  • using debugger I did not seem to witness any returned object from helpers.read. Commented Jul 29, 2019 at 21:32

1 Answer 1

1

For the asynchronous step to work, you have to either declare you are returning a Promise or that the function is async. Async/await is actually using promises under the hood, but it's a cleaner syntax.

For the Promise version, you have to return the value you want with the resolve function, and throw the error with the reject function.

exports.read = (spreadsheetId, range) => {
    return new Promise((resolve, reject) => {
        const sheets = google.sheets({ version: 'v4', auth: oAuth2Client });

        sheets.spreadsheets.values.get({
            spreadsheetId,
            range,
        })
        .then(data => {
            resolve(data.values);
        })
        .catch(err => reject(err));
    });
};

When you are using async/await, you can wrap the query in a try/catch and throw the error if it fails.

exports.read = async (spreadsheetId, range) => {
    const sheets = google.sheets({ version: 'v4', auth: oAuth2Client });
    try {
        const data = await sheets.spreadsheets.values.get({
            spreadsheetId,
            range,
        })
        return data.values;
    } catch(err) {
        throw err;
    }
};

I don't use underscore so I'm not sure what you were trying to return here. I assume that data is the result of the query and you were trying to pass out values?

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.