Query func error "misplaced await"

I try to implement a query function that calls an async function but, I am facing the error “misplaced await”.

I have the feeling I am hitting the limitation described in this post but, hopefully, I am “just” missing something.

Any idea how can I solve this?

import Error "mo:base/Error";

actor Echo {

  public query func say(phrase : Text) : async Text {
      await check_permission(phrase); // <-- misplaced await

      return phrase;
  };

  private func check_permission(phrase: Text) : async () {
    if (phrase == "no") {
       throw Error.reject("No permission.");
    }
  };
};

P.S.: Long story short. I have to transform my shared functions (“getter”) to query in order to improve the performance of the readonly queries of my web app.

On the other side, as we have users, I have implemented a permission check that throw errors if access is not granted. Therefore throw Error.reject which, I think, requires the function to be async.

Yes, you’ve hit the limitation.

A workaround, that will also greatly improve your perf and keep execution of the check atomic, is to rewrite your check to return a plain Bool (not async Bool) and test and throw at the former callsites.

1 Like

It’s what I had in mind too but, thought it was worth a try to ask first before refactoring all my code :wink:.

Thanks for the confirmation!

Here the resulting canister if someone is interested: deckdeckgo/studio/canisters/users at feat/internet-computer · deckgo/deckdeckgo · GitHub

I modified the permission check with boolean and also wrapped the result in an object that contains both result and a potential error label. Doing so, in my actor, I am able to check if there were errors and, in such cases, still throw Exception.

1 Like