haxetink / tink_await

Haxe async/await
MIT License
58 stars 15 forks source link

Optimize boolean short-circuiting #29

Open gene-pavlovsky opened 5 years ago

gene-pavlovsky commented 5 years ago

Consider the following example:

  @async public function deleteUser(id:Int, user:UserSession):Noise {
    var authorized = user.isSuperUser || (user.isAdmin && @await isNotAdmin(id));
    if (!authorized) throw new Error(Unauthorized, "unauthorized");
    return db.User.delete({where: u -> u.id == id}).next(_ -> Noise);
  }

  function isNotAdmin(id:Int):Promise<Bool>
    return db.User.where(User.id == id).first()
      .next(u -> u.roles & (UserRole.ADMIN | UserRole.SUPERUSER) == 0);

If isNotAdmin would be a sync function, it would not be evaluated in case the current user is either a SuperUser (can delete any user), or a regular non-admin user (can't delete any user). The way tink_await transforms this code, isNotAdmin(id) is eagerly evaluated, and only then the whole expression is evaluated.

Would it be possible to optimize this?