Aller au contenu principal

Creating Tasks

Different ways to create Task instances

API

Overview​

Tasks can be created in multiple ways depending on your use case. The main entry point is Task.create, but there are also convenience methods for common patterns.

Task.create​

The primary way to create a task with custom logic:

Synchronous​


import { Task } from '@w5s/task';

// Synchronous computation
const randomNext = Task.create(() => Task.ok(Math.random()));

// Execute synchronously
const result = Task.run(randomNext); // Result.Ok([generated number])

Asynchronous​

import { Task } from '@w5s/task';

// With error handling
const fetchTask = Task.create(async () => {
try {
const response = await fetch('/api/data');
return Task.ok(await response.json());
} catch (error) {
return Task.error(new NetworkError({ cause: error }));
}
});

// Execute asynchronously
const result = await Task.run(fetchTask); // Result.Ok([json response]) or Result.Error(NetworkError())

Task.resolve / Task.reject​

Create tasks that immediately resolve or reject:

import { Task } from '@w5s/task';

// A task that resolves with a value
const resolvedTask = Task.resolve(42);

// A task that rejects with an error
const rejectedTask = Task.reject(new Error('Something went wrong'));

Task.ok / Task.error​

Shorthand for creating Result objects within tasks:

import { Task } from '@w5s/task';

const myTask = Task.create(() => {
const random = Math.random();
if (random > 0.5) {
return Task.ok(random);
}
return Task.error('Too low');
});

Task.tryCall​

Safely wrap functions that might throw:

import { Task } from '@w5s/task';

const parseJSON = (text: string) =>
Task.tryCall(
() => JSON.parse(text),
(error) => new ParseError({ message: 'Invalid JSON', cause: error })
);

Task.from (Advanced)​

Lower-level API for creating tasks with full control over execution:

import { Task } from '@w5s/task';

const delayedTask = Task.from(({ resolve, reject, canceler }) => {
const timeoutId = setTimeout(() => resolve(42), 1000);

// Setup cancellation
canceler.addEventListener('abort', () => clearTimeout(timeoutId));
});