正确的方法将AxiosPromise更改为常规Promise,同时避免了promise构造函数的反模式

时间:2018-10-23 08:00:26

标签: javascript typescript promise

提供以下打字稿功能:

public load(filter: IFilter): Promise<Material[]> {
    return axios.get<Material[]>("data.json");
}

Typescript返回以下错误(类型不兼容)

[ts]
Type 'AxiosPromise<MaterialSpectrum[]>' is not assignable to type 'Promise<MaterialSpectrum[]>'.
  Types of property 'then' are incompatible.
    Type '<TResult1 = AxiosResponse<MaterialSpectrum[]>, TResult2 = never>(onfulfilled?: (value: AxiosResponse<MaterialSpectrum[]>) => TResult1 | PromiseLike<TResult1>, onrejected?: (reason: any) => TResult2 | PromiseLike<TResult2>) => Promise<...>' is not assignable to type '<TResult1 = MaterialSpectrum[], TResult2 = never>(onfulfilled?: (value: MaterialSpectrum[]) => TResult1 | PromiseLike<TResult1>, onrejected?: (reason: any) => TResult2 | PromiseLike<TResult2>) => Promise<...>'.
      Types of parameters 'onfulfilled' and 'onfulfilled' are incompatible.
        Types of parameters 'value' and 'value' are incompatible.
          Type 'AxiosResponse<MaterialSpectrum[]>' is not assignable to type 'MaterialSpectrum[]'.
            Property 'length' is missing in type 'AxiosResponse<MaterialSpectrum[]>'.

为了避免仅返回或强制转换AxiosPromise,我尝试了以下操作:
在纸上看起来正确。

    return new Promise((resolve, reject) =>
        axios.get<Material[]>("data.json")
            .then((data) => resolve(data.data))
            .catch((data) => reject(data.data)));

但是它显然违反了Promise constructor anti pattern

1 个答案:

答案 0 :(得分:1)

您可以在Promise.resolve中“包装” axios.get返回的诺言,就像这样

.then和.catch也需要重写(我使用新语法简化了它们,以解构函数参数-可能在那里使用了错误的术语)

return Promise.resolve(axios.get<Material[]>("data.json"))
.then(({data}) => data)
.catch(({data}) => { throw data; });