首页 > 解决方案 > 通过 GAS 与多个用户共享 Google 日历 - 循环不起作用

问题描述

我正在尝试使用 GAS 与所有家长共享课堂日历。从 v3/acl 资源复制的代码可用于授权一个用户,但我无法弄清楚为什么我的修改使其循环遍历users数组中的其他用户不起作用。任何帮助,将不胜感激。

日志文件显示“用户:user0@gmail.com,Users.length:2.0,周期:0.0”

/**
 * Set up calendar sharing for a single user. Refer to 
 * https://developers.google.com/google-apps/calendar/v3/reference/acl/insert.
 *
 * @param {string} calId   Calendar ID
 * @param {string} user    Email address to share with
 * @param {string} role    Optional permissions, default = "reader":
 *                         "none, "freeBusyReader", "reader", "writer", "owner"
 *
 * @returns {aclResource}  See https://developers.google.com/google-apps/calendar/v3/reference/acl#resource
 */
function shareCalendar(calId,user,role) {
  var calId = "somecalendar@group.calendar.google.com";
  var users = ["user0@gmail.com","user1@gmail.com"];
  var user = "";
  for (i = 0; i < users.length; i++) {
    var user = users[i];
    role = role || "reader";
    Logger.log('User: %s, Users.length: %s, Cycle: %s',user, users.length,i);

    var acl = null;

    // Check whether there is already a rule for this user
    try {
      var acl = Calendar.Acl.get(calId, "user:"+user);
    }
    catch (e) {
      // no existing acl record for this user - as expected. Carry on.
    }

    if (!acl) {
      // No existing rule - insert one.
      acl = {
        "scope": {
          "type": "user",
          "value": user
        },
        "role": role
      };
      var newRule = Calendar.Acl.insert(acl, calId);
    }
    else {
      // There was a rule for this user - update it.
      acl.role = role
      newRule = Calendar.Acl.update(acl, calId, acl.id)
    }
    return newRule;
  }
}

标签: google-apps-scriptgoogle-calendar-apigoogle-classroom

解决方案


因为它第一次通过循环执行了返回。这终止了函数的执行。这就是 return 所做的。

return return 语句结束函数执行并指定要返回给函数调用者的值。


推荐阅读