TSlint返回承诺字符串数组

时间:2018-09-12 06:40:23

标签: typescript promise return-type tslint

如何使函数返回promise-string-array?

  this.MyArray= [];

  async OtherFunction() {
    this.MyArray= await this.callQuery(); //***
  }

  async callQuery() {
    return await new Promise((resolve, reject) => {
      this.httpclient.get('').subscribe(response => {
        resolve(response);
      });
    });
  }

在此示例中,我的tslint在与this.MyArray的链接中的//***上引发了错误。错误显示:Type '{}' is not assignable to type 'any[]。但是,当像这样向callQuery()函数添加类型声明时:

async callQuery(pQuery): string[] {

然后我在string[]上遇到tslint错误,说:Type 'string[]' is not a valid async function return type in ES5/ES3 because it does not refer to a Promise-compatible constructor value

我要弄清楚的是像我在第一段中所解释的那样,清除this.MyArray上的tslint错误。我认为解决此问题的方法是让callQuery()返回一个数组,但我不知道如何在没有tslint抱怨的情况下使此工作正常。

注意:我的callQuery()函数将始终返回一个数组。因此代码正常运行,只是tslint给了我错误。

1 个答案:

答案 0 :(得分:1)

如果您特别想返回string [],则需要以通用类型(在本例中为string [])返回promise。

就像Sirko所说的那样,当您已经创建了新的Promise时,使用async / await无效。

callQuery(): Promise<string[]> {
    ...handlePromise
}    
相关问题