javascript - 返回空洞的 promise

标签 javascript angular typescript promise

我正在实现这个 button在我的应用程序中。

在我的按钮组件中我有:

  @Input() callback: () => Promise<null>;
  onClick() {
    this.spinnerService.show();
    this.callback().then(() => {
      this.spinnerService.hide();
    }, () => {
      this.spinnerService.hide();
    });
  }

(我不使用 async/await 因为“技术负责人”不想要我)

组件模板:

<my-button [callback]="doSomething">
</my-button>

当我将这种代码传递给组件的输入时,一切正常:

doSomething = () => {
  return myService.doSomething()
    .toPromise()
    .then((response) => console.log('promise resolved'));
}

但是我需要提前中断这个函数:

doSomething() {
  if (condition) {
    return;
  }
  return myService.doSomething()
    .toPromise()
    .then((response) => console.log('promise resolved'));
}

我明白了

ERROR TypeError: Cannot read property 'then' of undefined

我试过用同样的结果强制 promise

  if (condition) {
    return Promise.resolve(null);
    // or
    return new Promise((resolve) => { resolve(null); });
  }

最佳答案

对于这个输入

@Input() callback: () => Promise<null>;

不能保证它被赋予了正确的值。额外检查是否 callback指定应添加。

一个更安全的管理方法是使用 async在这些地方发挥作用是因为它们始终使用 promise:

  async onClick() {
    this.spinnerService.show();

    try {
      if (this.callback)
        await this.callback()
    } finally {
      this.spinnerService.hide();
    }
  }

doSomething应该无条件地返回一个 promise ,这也可以用 async 来解决。 :

async doSomething() {
  if (!condition)
    return myService.doSomething().toPromise();
}

如果async由于某些原因不能使用函数(虽然没有好的函数,因为它们符合规范,是 TypeScript 中的一等公民),promises 应该在函数中一致地处理(也有助于测试)。 doSomething类型不正确,这会导致不正确的函数返回。应该是:

  onClick(): Promise<void> {
    this.spinnerService.show();

    return Promise.resolve(this.callback ? this.callback() : undefined)
    .catch(() => {})
    .then(() => {
      this.spinnerService.hide();
    });
  }

doSomething(): Promise<void> {
  if (condition) {
    return Promise.resolve();
  }

  return myService.doSomething().toPromise();
}

以及 callback 的类型将是 Promise<void> , 不是 Promise<null> .

常规(非箭头)doSomething方法应绑定(bind)到 this在构造函数中。

关于javascript - 返回空洞的 promise ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49302235/

相关文章:

javascript - 在 Angular 2 中路由期间保持组件事件

typescript - 在考虑中间可选键的情况下推断嵌套值类型

typescript - TypeScript 编译中的实验性装饰器警告

javascript - 带有 MongoDB 的客户端 jQuery 应用程序

javascript - js问题输入文件按钮不起作用,弹出窗口不会显示

html - 带有超链接的 Angular 5 DomSanitizer

angular - 如何通过间隔运算符发送请求?

javascript - Facebook 点赞视频自动播放和暂停

javascript - 更新后的几分钟内服务器未分发更新的 javascript 文件

typescript - 如何使 Typescript 检测到带有区分大小写拼写错误的导入路径错误?