代码之家  ›  专栏  ›  技术社区  ›  bensiu CandorZ

如何声明任何对象数组的承诺返回

  •  0
  • bensiu CandorZ  · 技术社区  · 8 年前

    我尝试从将返回对象数组承诺的方法定义返回:

    public readAll( ) : Promise<any[]> {
    
      this.handler.getObject( {
        Bucket              : this.bucket,
        Key                 : this.tableName + '.json',
        ResponseContentType : 'text/plain'
      } )
      .promise( )
      .then( file => { 
    
        const data : any[] = this._parseData( file.Body.toString( ) ); 
    
        return new Promise( ( resolve ) => data );
      } )
      .catch( error => {
    
        return this.writeAll( );
      } );
    }
    

    然而,我面临的错误是“[ts]声明类型既不是“void”也不是“any”的函数必须返回值。”

    我做错了什么?

    2 回复  |  直到 8 年前
        1
  •  7
  •   Sajeetharan    8 年前

    正如错误所述,函数readAll期望返回类型 Promise<any[]> 尝试在 readAll

    public readAll() : Promise < any[] > {
      return this.handler.getObject({
        Bucket: this.bucket,
        Key: this.tableName + '.json',
        ResponseContentType: 'text/plain'
      })
        .promise()
        .then(file => {
          const data: any[] = this._parseData(file.Body.toString());
          return data;
        })
        .catch(error => {
          return this.writeAll();
        });
    
    }
    
        2
  •  0
  •   bensiu CandorZ    8 年前

    安德烈·尼古拉连科(Andrii Nikolaienko)的建议导致了一个有效的解决方案:

    protected readAll( ) : Promise<any[ ]> {
    
      return new Promise( resolve => {
    
        this.handler.getObject( {
          Bucket              : this.bucket,
          Key                 : this.tableName + '.json',
          ResponseContentType : 'text/plain'
        } )
        .promise( )
        .then( file => { 
    
          const data : any[] = this._parseData( file.Body.toString( ) ); 
          resolve( data );
        } )
        .catch( error => {
    
          resolve( this.writeAll( [ ] ) );
        } )
      } );
    }
    

    谢谢你的建议。

    推荐文章