理解带有未授权承诺的消息[重复]

问题描述 投票:1回答:1

在我的TypeScript应用程序中,我使用Promise<void>,它存储在本地的类范围变量中。可能会调用同一类的某个方法,然后等待此承诺得到解决或拒绝,但这并不总是会发生。承诺很可能在没有任何人听的情况下开始。当没有人听到承诺时,我在控制台中收到以下错误:

Uncaught (in promise) undefined

承诺中包含的工作成功运行没有问题。只是这个错误信息,我想确定它的含义。我是否正确地假设这个错误消息只是意味着没有人正在倾听决定或拒绝承诺,因此,它只是通过自己的工作来完成它的工作?反正有没有抑制此错误消息?

承诺看起来像这样:

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();
    });
});
javascript typescript promise
1个回答
2
投票

我不认为这会解决你的问题,但我注意到你不必要地围绕另一个承诺创造额外的承诺。由于requestInitialization()返回一个promise,因此根本不需要调用new Promise。在承诺上调用.then会自动产生新的承诺。

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
© www.soinside.com 2019 - 2024. All rights reserved.