1

In my TypeScript application I make use of Promise<void>, which is stored within a local class-wide variable. It is possible that some method of the same class is called which then waits on this promise to get resolved or rejected, but this does not always happen. It is very possible that the promise is started without anybody listening to it. When nobody is listening to the promise, I get the following error in the console:

Uncaught (in promise) undefined

The job contained within the promise runs trough successfully without problems. It is just this error message that I would like to be sure about its meaning. Am I right to assume that this error message just means that nobody is listening to the resolve or reject of the promise, hence, it just does its job by its own? Is there anyway to suppress this error message?

The promise looks like this:

private apiInitialization: Promise<void>;

...

this.apiInitialization = new Promise<void>((resolve, reject) => {
    this.siteService.requestInitialization().then((response: RequestResponse) => {
        // Do some stuff.
        // Resolve promise.
        resolve();
    }).catch(() => {
        // Reject promise.
        reject();
    });
});
Socrates
  • 8,724
  • 25
  • 66
  • 113

1 Answers1

2

I don't think this will solve your problem, but i notice you're unnecessarily creating an extra promise around another promise. Since requestInitialization() returns a promise, you don't need to call new Promise at all. Calling .then on a promise automatically produces a new promise.

this.apiInitialization = this.siteService.requestInitialization()
  .then((response: RequestResponse) => {
    // Do some stuff.

    // If you want apiInitialization to be a Promise<void>, do nothing further.
    // If instead you want the promise to resolve to something, return that something here.
  });
  // No need to do a .catch unless you want to handle the error here
Nicholas Tower
  • 72,740
  • 7
  • 86
  • 98
  • The OP doesn't need the `then` either! That variable contains a promise the OP uses elsewhere with `then`. – Randy Casburn Mar 10 '19 at 22:02
  • 1
    It's possible they need it, depending on what `// Do some stuff.` entails. – Nicholas Tower Mar 10 '19 at 22:04
  • That is because (speculation) the OP doesn't _really_ understand how promises work. Otherwise, the OP would _never_ type a Promise as `void`. It is most likely the OP wants to _do some stuff_ elsewhere in the component (the S in SOLID). – Randy Casburn Mar 10 '19 at 22:08
  • Admittedly the posted example is not flawless and the way of rejection should be handled differently. This did help though and behind `// Do some stuff` is a bit of code I really need at that place. – Socrates Mar 10 '19 at 23:56