1

I'm using Google Sheets API to copy a sheet, and I want to pass the ID of the new sheet into a variable.

I can successfully get the sheet ID within the callback function (using result.data.sheetId), but I'm struggling to use it outside of the function.

I'm using async / await syntax, and I have also experimented with utils.promisify, with no luck!

async function copySheet(jwt, apiKey, spreadsheetId, range) {

  const sheets = google.sheets({ version: 'v4' });

  let newSheetId = await sheets.spreadsheets.sheets.copyTo({
    "spreadsheetId": spreadsheetId,
    "sheetId": 0,
    "auth": jwt,
    "key": apiKey,
    "resource": {
      "destinationSpreadsheetId": spreadsheetId,
    }
  }, function (err, result) {
    if (err) {
      throw err;
    }
    console.log(result.data.sheetId);
    return result.data.sheetId;
  });

  console.log(newSheetId);

}

The first console.log shows the number I want, but the second logs undefined.

Do you have any suggestions to allow me to use the sheetId outside of the callback function?

1 Answer 1

1

How about this modification? Please think of this as just one of several answers.

Modified script:

Please modify your script as follows.

From:

let newSheetId = await sheets.spreadsheets.sheets.copyTo({
  "spreadsheetId": spreadsheetId,
  "sheetId": 0,
  "auth": jwt,
  "key": apiKey,
  "resource": {
    "destinationSpreadsheetId": spreadsheetId,
  }
}, function (err, result) {
  if (err) {
    throw err;
  }
  console.log(result.data.sheetId);
  return result.data.sheetId;
});

console.log(newSheetId);

To:

let res = await sheets.spreadsheets.sheets.copyTo({
  "spreadsheetId": spreadsheetId,
  "sheetId": 0,
  "auth": jwt,
  "key": apiKey,
  "resource": {
    "destinationSpreadsheetId": spreadsheetId,
  }
});

let newSheetId = res.data.sheetId;
console.log(newSheetId);

Note:

  • From your question, I could confirm that you have already been able to use Sheets API.
  • spreadsheets.sheets.copyTo() uses POST method. So in this case, API key cannot be used. I think that even when key: apiKey is removed, the script works.

Reference:

If this was not the result you want, I apologize.

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.