代码之家  ›  专栏  ›  技术社区  ›  7ball

编写清洁承诺完成闭包

  •  3
  • 7ball  · 技术社区  · 7 年前

    this.myService.createFoo(data).subscribe(
      (result: any) => {
        resolve({success: true, data: result});
      },
      err => {
        resolve({success: false, message: err});
      });
    
    this.myService.updateFoo(data).subscribe(
      (result: any) => {
        resolve({success: true, data: result});
      },
      err => {
        resolve({success: false, message: err});
      });
    

    我该如何重写subscribe方法的完成闭包,以避免像这样重复代码?。谢谢

    3 回复  |  直到 7 年前
        1
  •  2
  •   Rob M.    7 年前

    一种方法是将回调提取到泛型函数中,然后只传递这些函数:

    const successHandler = (data: any) => resolve({success: true, data });
    const errorHandler = (message) => resolve({success: false, message });
    
    this.myService.createFoo(data).subscribe(successHandler, errorHandler);
    this.myService.updateFoo(data).subscribe(successHandler, errorHandler);
    

    Promise (我假设您发布的代码在其中),您可以使用curry处理程序:

    some-util-library.js

    const handlers = resolve => ({
        success: (data: any) => resolve({success: true, data }),
        error: (message) => resolve({success: false, message })
    });
    export { handlers };
    

    import { handlers } from './some-util-library.js';
    ... other code
    const { success, error } = handlers(resolve);
    this.myService.createFoo(data).subscribe(success, error);
    this.myService.updateFoo(data).subscribe(success, error);
    
        2
  •  0
  •   Lukas S.    7 年前

    我假设您正试图返回一个承诺,并且您发布的代码包含在一个类似以下内容的方法中:

    create(): Promise<any> {
      const data = 'whatever';
      return new Promise<any>((resolve, reject) => {
        this.myService.createFoo(data).subscribe(
          (result: any) => {
            resolve({ success: true, data: result });
          },
          err => {
            resolve({ success: false, message: err });
          });
      });
    }
    

    toPromise 操作人员如果您尚未:

    import 'rxjs/add/operator/toPromise';
    

    然后,将其与 async await

    async create(): Promise<any> {
      const data = 'whatever';
      try {
        const result = await this.myService.createFoo(data).toPromise();
        return { success: true, data: result }
      } catch (err) {
        return { success: false, message: err };
      }
    }
    
        3
  •  0
  •   Jaime    7 年前