0

I like to know what does a Promise<void> mean? For example in the following code:

import { Stan } from 'node-nats-streaming';
import { Subjects } from './subjects';

interface Event {
  subject: Subjects;
  data: any;
}

export abstract class Publisher<T extends Event> {
  abstract subject: T['subject'];
  protected client: Stan;

  constructor(client: Stan) {
    this.client = client;
  }

  publish(data: T['data']): Promise<void> {
    return new Promise((resolve, reject) => {
      this.client.publish(this.subject, JSON.stringify(data), (err) => {
        if (err) {
          return reject(err);
        }
        console.log('Event published to subject', this.subject);
        resolve();
      });
    });
  }
}

The publish method returns a Promise<void> but as you can see the stan publish method that has been used inside the publish method should return a string like (method) Stan.publish(subject: string, data?: string | Uint8Array | Buffer | undefined, callback?: AckHandlerCallback | undefined): string.

I can't understand what Promise<void> looks like and how does it get matched with the expected string that stan.publish():string method should return?

GoodMan
  • 542
  • 6
  • 19
  • 1
    `Promise` is just a promise that contains a value that has no meaning. The type `void` is just a "contract" where the end user is given a disclaimer that the value they get doesn't mean anything. – kelsny Sep 29 '22 at 18:33
  • 1
    Why would you expect it to return a type of `Stan.publish(...)`? You are simply invoking the publish function, and actually not returning it with the resolve function. You are calling resolve as `resolve()`, which is essentially resolving the promise with nothing, hence `Promise` – Terry Sep 29 '22 at 18:36
  • "[H]ow does it get matched"? It doesn't. The string returned by `this.client.publish()` is thrown away. Probably because the author didn't know how to get the return value into the `resolve` in the callback. – Heretic Monkey Sep 29 '22 at 18:43
  • Please convert this code snippet to a [mre] that directly demonstrates your issue if someone pastes it, as-is, into a standalone IDE. Unless the question is *about* whatever `Subjects` is, you probably should remove references to it. It is rare that a snippet of code from an external source is a valid [mre] suited to Stack Overflow. – jcalz Sep 29 '22 at 18:46

0 Answers0