Ready Callback for Asynchronous Task Coordination

4.0.0 · active · verified Tue Apr 21

ready-callback is a utility library designed to manage the readiness of a server or application after a series of asynchronous tasks have completed. It's particularly useful in scenarios where a server needs to wait for database connections, external service initializations, or other long-running setup processes before it can start accepting requests. The current stable version is 4.0.0, released in October 2023. This package has a moderate release cadence, with major versions aligning with Node.js LTS updates. Key differentiators include its simple callback-based API for registering tasks, robust error handling with optional 'weak' dependencies, and configurable timeouts for individual tasks or the overall ready process. It also provides status updates during task completion. Originally used heavily within the Egg.js framework ecosystem, it offers a pragmatic solution for orchestrating application startup sequences.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates initializing `ready-callback` with Koa, registering multiple asynchronous tasks, handling their completion, and launching the server only when all tasks are complete, including error and timeout handling.

import Koa from 'koa';
import ready from 'ready-callback';

const app = new Koa();
const appReady = ready();

// Mix the ready-callback functionality into your Koa application instance
appReady.mixin(app);

// Register an asynchronous service task
const dbConnectDone = app.readyCallback('databaseConnection');
setTimeout(() => {
  console.log('Database connected!');
  dbConnectDone(); // Mark the task as complete
}, 1000);

// Register another async task, e.g., loading config
const configLoadDone = app.readyCallback('configurationLoading', { timeout: 500 });
setTimeout(() => {
  console.log('Configuration loaded!');
  configLoadDone();
}, 300);

// The main application logic waits for all registered tasks
app.ready(() => {
  console.log('All async tasks are ready. Launching server...');
  app.listen(3000, () => {
    console.log('Server listening on http://localhost:3000');
  });
});

// Example of error handling for a task
app.on('error', (err, ctx) => {
  console.error('Server error or ready-callback error:', err.message);
  // Handle errors emitted by ready-callback if a task fails and is not weak
});

// Example of timeout handling
app.on('ready_timeout', (id) => {
  console.warn(`Task '${id}' timed out!`);
});

view raw JSON →