José AlvarezJ
Convex Community16mo ago
3 replies
José Alvarez

Can actions actually return a value?

The documentation is not very clear about whether actions can have a return value or not. If they can't, I'd apprecaite it if the documentation could acknowledge this clearly. If they can, I'd appreciate a clear example showcasing how to do this.

For example, I would like to have this kind of action.

export const createThread = internalAction({
  handler: async () => {
    const apiKey = process.env.OPENAI_API_KEY!;
    const openai = new OpenAI({ apiKey });

    const thread = await openai.beta.threads.create();

    return thread.id; // Also, could I return the thread object?
  },
});


I am not interested in calling this action in the front-end (hence internalAction). I've seen in the demos on GitHub (https://github.com/get-convex/convex-demos) examples of actions being called in the front-end (https://github.com/get-convex/convex-demos/tree/main/vector-search) to get a return value, but not examples of actions returning something in the backend.

Indeed, my seemingly only option to run an action in the backend is with the scheduler:

const threadId: string = await ctx.scheduler.runAfter(
      0,
      internal.openai.createThread
    );


The above schedules the action to run in the future, which is not what I want.

I want to actually await the action and get its return value before executing the rest of the backend code (in this case, a mutation), is there a way to do this?

I also tried to call openai.beta.threads, but the linter complains that this expression it's not callable.

Originally I tried to just use a normal function, or what it's equivalent, just call openai.beta.threads.create() inside of my mutation, but I got this:

Uncaught Error: Uncaught Error: Can't use setTimeout in queries and mutations. Please consider using an action. See https://docs.convex.dev/functions/actions for more details.
    at fetchWithTimeout [as fetchWithTimeout] (../node_modules/openai/src/core.ts:556:11)


Thank you!
GitHub
Demo apps built on Convex. Contribute to get-convex/convex-demos development by creating an account on GitHub.
GitHub - get-convex/convex-demos: Demo apps built on Convex.
GitHub
Demo apps built on Convex. Contribute to get-convex/convex-demos development by creating an account on GitHub.
convex-demos/vector-search at main · get-convex/convex-demos
Was this page helpful?