Fulfill the promise within the callback

When using my client-websocket, I have the ability to register callbacks for specific events such as opening or closing the connection. In these callbacks, I aim to resolve a promise in order to await the events from an external source, especially for unit tests. The code snippet below illustrates what I am trying to achieve:

let wsOnOpenPromise = new Promise<void>(resolve => { /* ??? */ });
let wsOnClosePromise = new Promise<void>(resolve => { /* ??? */ });
const ws = new WebsocketBuilder(url)
    .onOpen((i, e) => { /* resolve wsOnOpenPromise here */ })
    .onClose((i, e) => { /* resolve wsOnClosePromise here */ })
    .build();
await wsOnOpenPromise;
shutdownServer(); /* Shutdown the server here, the on-close event should fire */
await wsOnClosePromise;

How can I accomplish this? It appears that I need to define the promises upfront and resolve them within the callbacks so they can be awaited as shown in the code snippet.

Answer №1

Here's the solution:

const ws = new WebsocketBuilder(url);
const onOpen = new Promise(ws.onOpen.bind(ws));
const onClose = new Promise(ws.onClose.bind(ws));
ws.build();
await onOpen;
shutdownServer(); /* Close the server here, triggering the on-close event */
await onClose;

Explanation:

The expression:

new Promise(ws.onOpen.bind(ws))

...is similar to:

new Promise((resolve, reject) => ws.onOpen(resolve, reject))

Since onOpen only takes one argument, reject is not needed. This can be further simplified to:

new Promise((resolve, reject) => ws.onOpen((i, e) => resolve(i, e), reject))

Similarly, resolve only takes one argument, so we can reduce it to:

new Promise(ws.onOpen.bind(ws))

The same concept applies to onClose as well.

Answer №2

This is how I managed to make it work:

let opening = () => {};
let closing = () => {};
const openingPromise = new Promise<void>(resolve => opening = resolve);
const closingPromise = new Promise<void>(resolve => closing = resolve);
const websocket = new WebsocketBuilder(url)
    .onOpen((i, e) => { opening() })
    .onClose((i, e) => { closing() })
    .build();
await openingPromise;
/* Perform shutdown action here, the on-close event will trigger */
await closingPromise;

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Guide on setting up redux store from server component using next.js and app router

I'm currently working with Next.js 13, React, and Redux to handle state management. My main objective is to fetch initial data on the server side and present it on the client side. Although I assumed this would be a typical approach with Redux and Ne ...

The object might be undefined; TypeScript; Object

Why is it that the object may be undefined, even though it is hard-coded in my file as a constant that never changes? I've tried using ts-ignore without success. const expressConfig = { app: { PORT: 3000, standardResponse: `Server ...

Exploring matching routes with Next.js + Jest

Issue with Unit Testing MenuItem Component Despite my efforts to achieve 100% coverage in my component unit tests, I have encountered an uncovered branch specifically within the MenuItem component. To offer more insight, here is the parent component that ...

a callback may seem like it's not a function, but in reality, it is

This question might seem simple, but I'm struggling to grasp the concept of callbacks, especially in NodeJS. My issue arises when trying to retrieve data from MySQL, something that is usually straightforward in most programming languages: In my rout ...

TypeScript: displaying parameters

variable_field = [["S",".","."],[".","#","."],[".",".","T"]]; <ng-template ngFor let-array [ngForOf]="field_array" let-x="index"> <ng-t ...

TS & Angular: Unlocking the Power of Conditional Interfaces

My user component includes a variable called user, which can be either an Employee or a Student. In my HTML, I have an element {{ user.coure ?? user.department }} I'm encountering an issue in my HTML because some properties in the Employee interface ...

Calculate the variance between two variables

I am facing a challenge where I have an object and the 'Hours' field is saved as a string. I am looking to convert this string into actual hours and then calculate the difference between the two variables. const groupSchedule=[ {"days":"sat" ...

Expand row size in grid for certain row and item

For my project, I am utilizing a Grid layout to display 5 items per row. https://i.sstatic.net/PW6Gu.png Upon clicking on an item, my goal is to have the item detail enlarge by increasing the size of the HTML element. https://i.sstatic.net/nGj8l.png Is t ...

There is no index signature that includes a parameter of type 'number' on the specified type xx

Here are the data types I am currently utilizing: export interface IHelpDeskTextData { supportPaneltext: ContactHelpdeskContex[]; selected?: number | null; brandOptions?: string[]; textPanel?: ITextPanel[]; } export class ContactHelpdeskContex { ...

Expressjs - Error: Headers already sent to the client and cannot be set

After testing various solutions from others, I am still unable to resolve this error. My objective is to iterate through each item in the array sourced below: novel.ts export let indexList = (req: Request, res: Response) => { novel.getAllDocuments ...

Refresh Ionic 2 Platform

I'm currently working on an Ionic 2 app and whenever I make a change to the .ts code, I find myself having to go through a tedious process. This involves removing the platform, adding the Android platform again, and then running the app in Android or ...

What is the best method for comparing arrays of objects in TypeScript for optimal efficiency?

Two different APIs are sending me arrays of order objects. I need to check if both arrays have the same number of orders and if the values of these orders match as well. An order object looks like this: class Order { id: number; coupon: Coupon; customer ...

How can we leverage mapped types in TypeScript to eliminate properties and promisify methods?

Below is the provided code snippet: class A { x = 0; y = 0; visible = false; render() { return 1; } } type RemoveProperties<T> = { readonly [P in keyof T]: T[P] extends Function ? T[P] : never//; }; type JustMethodKe ...

What is the best way to delay a recursive JavaScript function for 3 seconds?

Before writing this post, I have already come across the following questions: how-to-pause-a-settimeout-call how-to-pause-a-settimeout-function how-to-pause-a-function-in-javascript delay-running-a-function-for-3-seconds Question The below code snipp ...

Is there a way to have my accordion adjust automatically?

I have developed a dynamic accordion component that populates its values from the parent component. However, I am facing an issue where each accordion does not respond individually to clicks. Whenever I click on any accordion, only the first one expands an ...

Configuring Jest with TypeScript: A guide to setting up and running tests across multiple files

Currently, I am diving into the world of TDD and attempting to create a basic test suite for my Node Express API. My project directory has the following structure: . └── root/ ├── src/ │ ├── services/ │ │ └─ ...

The left-hand operator in Typescript is not valid

I am a beginner in typescript and I have been following a tutorial called Tour of Heroes on Angular's website. In the final chapter of the tutorial, when I tried to use HTTP with the provided code, everything seemed to run fine but I encountered an er ...

Node_modules folder is excluded from Typescript compilation

I am struggling to understand why TypeScript is not compiling code from the node_modules folder. Below is the content of my tsconfig.json file: { "compilerOptions": { "rootDir": ".", "baseUrl": ".", "paths": { "shared": ["./src/shared ...

Navigating the enum data model alongside other data model types in Typescript: Tips and Tricks

In my different data models, I have utilized enum types. Is it possible to compare the __typename in this scenario? enum ActivtiyCardType { Dance, ReferralTransaction, } type ActivityCardData = { __typename:ActivtiyCardType, i ...

Leverage a custom server (such as NestJS) within NextJS to dynamically render targeted pages

I am experimenting with using NestJS as a custom server for NextJS, following the instructions in this article. Here is a simplified version of the code: @Controller('/') export class ViewController { @Get('*') async static(@Req() r ...