Skip to content

Commit

Permalink
Task perform()
Browse files Browse the repository at this point in the history
  • Loading branch information
Exelord committed Jan 20, 2023
1 parent c11946a commit 29a47da
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 10 deletions.
17 changes: 11 additions & 6 deletions src/task.ts
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,7 @@ export class Task<T> implements Promise<T> {
| null
| undefined
): Promise<TResult1 | TResult2> {
return this.execute().then(onfulfilled, onrejected);
return this.#execute().then(onfulfilled, onrejected);
}

catch<TResult = never>(
Expand All @@ -107,16 +107,16 @@ export class Task<T> implements Promise<T> {
| null
| undefined
): Promise<T | TResult> {
return this.execute().catch(onrejected);
return this.#execute().catch(onrejected);
}

finally(onfinally?: (() => void) | null | undefined): Promise<T> {
return this.execute().finally(onfinally);
return this.#execute().finally(onfinally);
}

execute(): Promise<T> {
this.#promise ??= this.#resolve();
return this.#promise;
perform(): Task<T> {
this.#execute();
return this;
}

async cancel(cancelReason = "Task has been cancelled."): Promise<void> {
Expand All @@ -138,6 +138,11 @@ export class Task<T> implements Promise<T> {
}
}

#execute(): Promise<T> {
this.#promise ??= this.#resolve();
return this.#promise;
}

async #resolve(): Promise<T> {
// We need to check if the task has been cancelled before we start the promise.
this.#abortController.signal.throwIfAborted();
Expand Down
8 changes: 4 additions & 4 deletions tests/vitest/task.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,14 +7,14 @@ import {
import { describe, test, expect } from "vitest";

describe("Task", () => {
describe("#execute", async () => {
describe("#perform", async () => {
test("fulfilled", async () => {
const task = createTask(() => Promise.resolve("Hello World"));

expect(task.status).toBe(TaskStatus.Idle);
expect(task.isIdle).toBe(true);

task.execute();
task.perform();

expect(task.status).toBe(TaskStatus.Pending);
expect(task.isPending).toBe(true);
Expand All @@ -34,7 +34,7 @@ describe("Task", () => {
expect(task.status).toBe(TaskStatus.Idle);
expect(task.isIdle).toBe(true);

task.execute();
task.perform();

expect(task.status).toBe(TaskStatus.Pending);
expect(task.isPending).toBe(true);
Expand All @@ -54,7 +54,7 @@ describe("Task", () => {

expect(task.status).toBe(TaskStatus.Idle);

task.execute();
task.perform();

expect(task.status).toBe(TaskStatus.Pending);

Expand Down

0 comments on commit 29a47da

Please sign in to comment.