问题
Folder sharing does not work on Google Shared Drive, so I am trying to automate sharing through Google Apps Script.
I tried to write code with reference to several examples, but I kept getting errors and asked questions.
I got an error saying:
'Cannot retrieve the next object: iterator has reached the end', and I confirmed that sharing of some files was not set.
Below is the code I wrote. How can I fix this problem?
function myFunction() {
  var folderid = ""
  var folder = DriveApp.getFolderById(folderid);
  var files = folder.getFiles();
  while (files.hasNext()) {
    Logger.log(files.next().getName());
    files.next().setSharing(DriveApp.Access.ANYONE_WITH_LINK, DriveApp.Permission.VIEW);
  }
}
    回答1:
Issue:
.next()  returns the next file in the folder. If folder has 1  file, files.hasNext() returns true and files.next() returns file1. Calling files.next() again returns
Cannot retrieve the next object: iterator has reached the end'
First call to iterator:file#1
Logger.log(files.next().getName());
Second call to iterator: next file(not available)
files.next().setSharing(DriveApp.Access.ANYONE_WITH_LINK, DriveApp.Permission.VIEW);
If folder had 5 files, Logger would've logged names of files 1,3 and 5.  Sharing would've been set on files 2 and 4.    
Solution:
Call files.next() only once after checking with files.hasNext()    
Snippet:
  while (files.hasNext()) {
    const nextFile = files.next();//one call
    Logger.log(nextFile.getName());
    nextFile.setSharing(DriveApp.Access.ANYONE_WITH_LINK, DriveApp.Permission.VIEW);
  }
References:
- Iterator
 - File iterator
 
来源:https://stackoverflow.com/questions/61237540/cannot-retrieve-the-next-object-iterator-has-reached-the-end-error-when-iterati