1

The variable ids is an array with different spreadsheet ids. I wrapped it around the request because I want to do the same thing on multiple spreadsheets, however, once inside the request the id just becomes synchronous and stays as the last element in the ids array. I want to make it so that the id is asynchronous and changes so that I can do the request on multiple ids.

for(var i = 0; i < num; i++) {
      var id = ids.slice(i, i+1);
      var params = {
        spreadsheetId: id,
        ranges: ['A3:L'],
        includeGridData: true,
      };

      var request = gapi.client.sheets.spreadsheets.get(branchParams);
      request.then(function(response) {
        console.log(id);

1 Answer 1

2

Try this:

const getSheets = (ids) => {
  return Promise.all(
    ids.map(id => {
      const params = {
        spreadsheetId: id,
        <...>
      }
      return gapi.client.sheets.spreadsheets.get(params)
    })
  )
}

This will call the api once for every id in your list and return the list of responses in a promise. You can use this function like this:

const doStuffWithSheets = async () => {
  const ids = [1, 2, 3]
  const sheetResponses = await getSheets(ids);
  sheetResponses.forEach(response => {
    console.log(response)
  })
}

Some documentation for reference:

Promise.all(): https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all

map(): https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map

async function: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function

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

2 Comments

I got this to work but how do I go about console.logging each id inside the forEach loop? Thanks.
It should be in the response. I think the response should look like this: developers.google.com/sheets/api/reference/rest/v4/… You can also use console.log(JSON.stringify(response, null, 2)); to print the full response and see whats inside

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.