Cannot retrieve the next object: iterator has reached the end error when iterating over shared Drive

馋奶兔 提交于 2021-01-04 05:35:38

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!