createScheduler
Стабильный · с 0.1.0
Создаёт планировщик диспатча, которым рантайм пользуется внутри. Две встроенные стратегии — 'microtask' и 'sync' — закрывают почти любые реальные потребности; createScheduler доступен для кастомной композиции рантайма, низкоуровневых тестов и бенчмарков.
Microtask-планировщик батчит поставленные в очередь задачи и осушает их в queueMicrotask. Sync-планировщик запускает задачи немедленно, в стеке вызывающей стороны.
import { createScheduler } from '@triggery/core';
Сигнатура
Заголовок раздела «Сигнатура»function createScheduler(strategy: SchedulerStrategy): SchedulerImpl;
type SchedulerStrategy = 'sync' | 'microtask';
type SchedulerImpl = {
enqueue(task: () => void): void;
flush(): void;
};Параметры
Заголовок раздела «Параметры»| Параметр | Тип | Описание |
|---|---|---|
strategy | 'sync' | 'microtask' | Политика диспатча. |
Возвращает
Заголовок раздела «Возвращает»SchedulerImpl:
| Метод | Описание |
|---|---|
enqueue(task) | Поставить thunk в очередь. Microtask: батчит до следующего осушения микротасок. Sync: запускает немедленно. |
flush() | Осушить отложенные задачи прямо сейчас. Для тестов и fireSync. Sync-планировщик очередь не держит, поэтому его flush — no-op. |
Примеры
Заголовок раздела «Примеры»Microtask-батчинг
Заголовок раздела «Microtask-батчинг»import { createScheduler function createScheduler(strategy: SchedulerStrategy): SchedulerImpl } from '@triggery/core';
const sched const sched: SchedulerImpl = createScheduler function createScheduler(strategy: SchedulerStrategy): SchedulerImpl ('microtask');
const log const log: number[] : number[] = [];
sched const sched: SchedulerImpl .enqueue function enqueue(task: Task): void (() => log const log: number[] .push Array<number>.push(...items: number[]): numberAppends new elements to the end of an array, and returns the new length of the array. (1));
sched const sched: SchedulerImpl .enqueue function enqueue(task: Task): void (() => log const log: number[] .push Array<number>.push(...items: number[]): numberAppends new elements to the end of an array, and returns the new length of the array. (2));
sched const sched: SchedulerImpl .enqueue function enqueue(task: Task): void (() => log const log: number[] .push Array<number>.push(...items: number[]): numberAppends new elements to the end of an array, and returns the new length of the array. (3));
// At this synchronous point, nothing has run yet.
console var console: Console .log Console.log(...data: any[]): voidThe **`console.log()`** static method outputs a message to the console.
[MDN Reference](https://developer.mozilla.org/docs/Web/API/console/log_static) ('queued', log const log: number[] ); // []
await Promise var Promise: PromiseConstructorRepresents the completion of an asynchronous operation .resolve PromiseConstructor.resolve(): Promise<void> (+2 overloads)Creates a new resolved promise. (); // drain microtasks
console var console: Console .log Console.log(...data: any[]): voidThe **`console.log()`** static method outputs a message to the console.
[MDN Reference](https://developer.mozilla.org/docs/Web/API/console/log_static) ('drained', log const log: number[] ); // [1, 2, 3]Синхронный диспатч
Заголовок раздела «Синхронный диспатч»import { createScheduler function createScheduler(strategy: SchedulerStrategy): SchedulerImpl } from '@triggery/core';
const sched const sched: SchedulerImpl = createScheduler function createScheduler(strategy: SchedulerStrategy): SchedulerImpl ('sync');
const log const log: number[] : number[] = [];
sched const sched: SchedulerImpl .enqueue function enqueue(task: Task): void (() => log const log: number[] .push Array<number>.push(...items: number[]): numberAppends new elements to the end of an array, and returns the new length of the array. (1));
sched const sched: SchedulerImpl .enqueue function enqueue(task: Task): void (() => log const log: number[] .push Array<number>.push(...items: number[]): numberAppends new elements to the end of an array, and returns the new length of the array. (2));
// Already executed inline.
console var console: Console .log Console.log(...data: any[]): voidThe **`console.log()`** static method outputs a message to the console.
[MDN Reference](https://developer.mozilla.org/docs/Web/API/console/log_static) (log const log: number[] ); // [1, 2]Изоляция ошибок в microtask-режиме
Заголовок раздела «Изоляция ошибок в microtask-режиме»import { createScheduler function createScheduler(strategy: SchedulerStrategy): SchedulerImpl } from '@triggery/core';
const sched const sched: SchedulerImpl = createScheduler function createScheduler(strategy: SchedulerStrategy): SchedulerImpl ('microtask');
sched const sched: SchedulerImpl .enqueue function enqueue(task: Task): void (() => {
throw new Error var Error: ErrorConstructor
new (message?: string, options?: ErrorOptions) => Error (+1 overload)
('oops');
});
sched const sched: SchedulerImpl .enqueue function enqueue(task: Task): void (() => {
console var console: Console .log Console.log(...data: any[]): voidThe **`console.log()`** static method outputs a message to the console.
[MDN Reference](https://developer.mozilla.org/docs/Web/API/console/log_static) ('still runs');
});
await Promise var Promise: PromiseConstructorRepresents the completion of an asynchronous operation .resolve PromiseConstructor.resolve(): Promise<void> (+2 overloads)Creates a new resolved promise. ();
// Output: "[triggery] scheduler task failed: Error: oops"
// Output: "still runs"Замечания
Заголовок раздела «Замечания»См. также
Заголовок раздела «См. также» createRuntime Рантайм автоматически выбирает планировщик per-trigger.
createFakeScheduler Планировщик с виртуальным временем для тестов.
Руководство по планированию Microtask vs sync — когда что выбирать.
Стратегии конкурентности Как асинхронные обработчики переплетаются по каждой стратегии.