Skip to content

Commit

Permalink
Allow trial on_finish methods to be async (#3182)
Browse files Browse the repository at this point in the history
  • Loading branch information
bjoluc authored Nov 8, 2023
1 parent 9926a79 commit 3855b5d
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 2 deletions.
5 changes: 5 additions & 0 deletions .changeset/old-moons-lay.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"jspsych": minor
---

Allow trial `on_finish` methods to be asynchronous, i.e. return a `Promise`. Prior to this, promises returned by `on_finish` were not awaited before proceeding with the next trial.
23 changes: 22 additions & 1 deletion packages/jspsych/src/timeline/Trial.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import TestPlugin from "../../tests/TestPlugin";
import { JsPsychPlugin, ParameterType } from "../modules/plugins";
import { Timeline } from "./Timeline";
import { Trial } from "./Trial";
import { parameterPathArrayToString } from "./util";
import { PromiseWrapper, parameterPathArrayToString } from "./util";
import {
SimulationOptionsParameter,
TimelineVariable,
Expand Down Expand Up @@ -168,6 +168,27 @@ describe("Trial", () => {
expect(onFinishCallback).toHaveBeenCalledWith(expect.objectContaining({ my: "result" }));
});

it("awaits async `on_finish` callbacks", async () => {
const onFinishCallbackPromise = new PromiseWrapper();
const trial = createTrial({
type: TestPlugin,
on_finish: () => onFinishCallbackPromise.get(),
});

let hasTrialCompleted = false;
trial.run().then(() => {
hasTrialCompleted = true;
});

await flushPromises();
expect(hasTrialCompleted).toBe(false);

onFinishCallbackPromise.resolve();
await flushPromises();

expect(hasTrialCompleted).toBe(true);
});

it("invokes the global `onTrialResultAvailable` and `onTrialFinished` callbacks", async () => {
const invocations: string[] = [];
dependencies.onTrialResultAvailable.mockImplementationOnce(() => {
Expand Down
2 changes: 1 addition & 1 deletion packages/jspsych/src/timeline/Trial.ts
Original file line number Diff line number Diff line change
Expand Up @@ -232,7 +232,7 @@ export class Trial extends TimelineNode {
);
Object.assign(this.result, extensionResults);

this.runParameterCallback("on_finish", this.getResult());
await Promise.resolve(this.runParameterCallback("on_finish", this.getResult()));

this.dependencies.onTrialFinished(this);
}
Expand Down

0 comments on commit 3855b5d

Please sign in to comment.