【问题标题】:How do you return a typed Promise你如何返回一个输入的 Promise
【发布时间】:2019-09-24 17:52:59
【问题描述】:

以下代码有效,但它承诺返回任何东西。我如何将其更改为承诺返回特定类型的 Promise 或 Promise 的联合? buildError 返回的内容也键入为 Response。

public async getSomething(userId: string): Promise<any> {
    return new Promise((resolve: any, reject: any) => 
    {
        this.axios().get(baseUrl + path, config)
            .then((response: any) => {
                if (response && response.data && response.status === 200) {
                    resolve(response.data);
                } else {
                    reject(this.buildError(response.status || 500, userId));
                }
            })
            .catch((response: any) => {
                logger.error(response);
                const status = response.response ? response.response.status : 500;
                reject(this.buildError(status, userId));
    }
}

如果我键入 Promise,intelliJ 会抱怨类型“{}”不能分配给类型“响应”,类型“{}”中缺少属性“foo”。我试图将所有解决和拒绝都输入为响应。我假设 '{}' 指的是 => {...},但不清楚如何输入。

【问题讨论】:

  • 使用new Promise 几乎总是不正确的。在这种情况下肯定是。

标签: typescript types


【解决方案1】:

最终做了这样的事情

public async getSomething(userId: string): Promise<Response> {
    return new Promise<Response>((resolve: any, reject: any) => 
    {
        this.axios().get(baseUrl + path, config)
            .then((response: any) => {
                if (response && response.data && response.status === 200) {
                    resolve(response.data);
                } else {
                    reject(this.buildError(response.status || 500, userId));
                }
            })
            .catch((response: any) => {
                logger.error(response);
                const status = response.response ? response.response.status : 500;
                reject(this.buildError(status, userId));
    }
}

【讨论】:

    【解决方案2】:

    更正确的代码版本:

    public getSomething(userId: string): Promise<any> {
    
      return this.axios().get(baseUrl + path, config)
         .then((response: any) => {
            if (response && response.data && response.status === 200) {
               return response.data;
             } else {
               throw response;
             }
          })
          .catch((response: any) => {
             logger.error(response);
             const status = response.response ? response.response.status : 500;
             throw this.buildError(status, userId);
          })
        }
    }
    

    最奇怪的是,您在 then 和 catch 子句中都有相同的信息。这是非常不寻常的,我怀疑您误解了您的“axois”库的工作方式,但是......抛出“响应”(虽然很奇怪)使其与您的原始帖子一致。

    可以使用 async/await 进一步简化此示例。您在示例中使用了 async 关键字(错误地),所以我假设您能够使用它:

    public getSomething(userId: string): Promise<any> {
    
      try {
        const response = await this.axios().get(baseUrl + path, config);
        if (response && response.data && response.status === 200) {
           return response.data;
        } else {
           throw response;
        }
      } catch (response) {
        logger.error(response);
        const status = response.response ? response.response.status : 500;
        throw this.buildError(status, userId);
      }
    
    }
    

    我们又抛出了响应,这很奇怪......

    深入了解您的 Axios 库,似乎默认情况下,当发生 HTTP 错误时,Axios 会抛出带有“响应”属性的错误。如果这是正确的,您的代码示例实际上应该如下所示:

    public getSomething(userId: string): Promise<any> {
    
      try {
        const response = await this.axios().get(baseUrl + path, config);
        return response.data;
      } catch (err) {
        logger.error(err);
        const status = err.response ? err.response.status : 500;
        throw this.buildError(status, userId);
      }
    
    }
    

    【讨论】:

      猜你喜欢
      • 2020-08-06
      • 2016-10-14
      • 2019-09-17
      • 2021-08-07
      • 2020-06-12
      • 1970-01-01
      • 2018-10-14
      • 2021-10-18
      • 2014-10-21
      相关资源
      最近更新 更多