Spacer
Yggdrasil Server includes a spacer utility to help you apply a minimal amount of time spacing between tasks, such as API requests your server may make.
Usage
Simply create a YggdrasilSpacer
object with your desired spacing,
then use enqueueTask
to schedule each task for execution:
src/handler.ts
// Wait 100ms between each API request
const spacer = new YggdrasilSpacer(100);
const tasks = [];
for (const item of items) {
tasks.push(spacer.enqueueTask(async () => {
await api.updateItem(item);
}));
}
await Promise.all(tasks);
console.log("Done updating all items (with minimum 100ms spacing between each update)!");
The asynchronous task passed to enqueueTask
will be called automatically
when time spacing allows. The Promise returned by enqueueTask
resolves
when the task is completed. Passing a task function is optional; if it is
omitted, enqueueTask
resolves and the next task's spacing starts
immediately when the current task is triggered.