Skip to main content
Version: 2.2.x

Waiters

ZilaWS has a unique function called waiter. Waiters (as their name suggests) can be awaited. They resolve when a MessageHandler on the other side of the connection resolves or returns thus making it perfect for retrieving data. However if the client or server does not respond in time, waiters will resolve as undefined.

  • Regular waiters wait for a response for the time specified by the maxWaiterTime property.
    • On the server side this is a property of the server object.
    • On the client side this is a property of the client object.
  • waiterTimeouts wait for a response for the time specified by the maxWaitingTime parameter in miliseconds.

Parameters

  • identifier: The name of the MessageHandler on the other side of the connection.
  • maxWaitingTime: This paramater overrides the maximum waiting time for the corresponding waiter or broadcastWaiter. The value is in miliseconds.
  • ...data: A waiter (or a send) can be given any number of any data.

Usage

Waiter

socket.waiter<T>(identifier: string, ...data: any[]): Promise<T | undefined>
socket.waiterTimeout<T>(identifier: string, maxWaitingTime: number, ...data: any[]): Promise<T | undefined>

OR

server.waiter<T>(socket: ZilaClient, identifier: string, ...data: any[]): Promise<T | undefined>
server.waiterTimeout<T>(socket: ZilaClient, identifier: string, maxWaitingTime: number, ...data: any[]): Promise<T | undefined>

BroadcastWaiter

These functions only return values from those clients which respond in time.

server.broadcastWaiter<T>(identifier: string, ...data: any[]): Promise<Array<T>>
server.broadcastWaiterTimeout<T>(identifier: string, maxWaiterTime: number, ...data: any[]): Promise<Array<T>>

Example

This example shows how a very basic blog should use ZilaWS to request a post's details from the clientside.

import { ZilaServer } from "zilaws-server";

interface IPost {
title: string;
date: Date;
author: string;
content: string;
likes: number;
}

//Setting up the server
const server = new ZilaServer({
port: 6678,
logger: true
});

function fetchPost(id: string): Promise<IPost> {
return new Promise((resolve) => {
//In reality this is the part where you'd fetch data from your database.
resolve({
title: "First post",
date: new Date(2024, 1, 5, 16, 44, 25),
author: "John",
content: "This is my first post. Hello, everyone!",
likes: 23
});
});
}

//Set up a MessageHandler
server.setMessageHandler("GetPostById", async (clSocket, postId: string) => {
console.log(`Fetch request for post ${postId} from ${clSocket.ip}`);
return await fetchPost(postId);
});

Console output:

Playground