API reference › @evolu/common › Task › promiseToTask
Call Signature
function promiseToTask<T>(start: (signal: AbortSignal) => Promise<T>): Task<T>;
Defined in: packages/common/src/Task.ts:3912
Creates a Task that awaits the promise start returns, through the
Run, whose abort ends the wait at once and ignores the late result,
also a late rejection.
It takes a function, not a promise, because a Task is lazy: each run starts
the operation anew, so retry, repeat, and timeout start
it again rather than await the promise of the first run. start gets the
Run's signal, so the operation itself can abort, as fetch and WebAuthn
allow. The signal also aborts once the Task settles, when the Run ends.
Without mapError, a rejection is a defect, for a promise that rejects only
on a bug. With it, the rejection becomes an Err with the error it
returns, as tryAsync maps one, and a mapError that throws is a
defect. A synchronous throw of start is a rejection, as in
tryAsync.
Example
import {
assertErr,
assertOk,
assertType,
createRun,
promiseToTask,
type Task,
type Typed,
} from "@evolu/common";
interface ReadError extends Typed<"ReadError"> {
readonly cause: unknown;
}
// A platform API that returns a promise and observes an AbortSignal.
const readSetting = (name: string, signal: AbortSignal): Promise<string> =>
name === "theme"
? Promise.resolve(signal.aborted ? "" : "dark")
: Promise.reject(new Error(`No setting ${name}`));
const readSettingTask = (name: string): Task<string, ReadError> =>
promiseToTask(
(signal) => readSetting(name, signal),
(cause) => ({ type: "ReadError", cause }),
);
// Without mapError, the Task has no error, as a rejection is a defect.
const themeTask = promiseToTask((signal) => readSetting("theme", signal));
assertType<typeof themeTask, Task<string>>();
await using run = createRun();
assertOk(await run(readSettingTask("theme")), "dark");
const missing = await run(readSettingTask("font"));
assertErr(missing);
assertType<typeof missing.error, ReadError>();
Call Signature
function promiseToTask<T, E>(
start: (signal: AbortSignal) => Promise<T>,
mapError: (error: unknown) => E,
): Task<T, E>;
Defined in: packages/common/src/Task.ts:3916
Maps a rejection to an error.