0

I try to define return from the method that would return Promise of an array of objects:

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( );
  } );
}

however, I am facing error "[ts] A function whose declared type is neither 'void' nor 'any' must return a value."

What am I doing wrong?

bensiu
  • 24,660
  • 56
  • 77
  • 117

2 Answers2

8

As the error says, your function readAll expects a return of type Promise<any[]> Try returning the Promise inside the 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();
    });

}
Sajeetharan
  • 216,225
  • 63
  • 350
  • 396
1

Suggestion from Andrii Nikolaienko lead to a working solution:

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( [ ] ) );
    } )
  } );
}

Thank you for the suggestion.

bensiu
  • 24,660
  • 56
  • 77
  • 117
  • 1
    Avoid the [`Promise` constructor antipattern](https://stackoverflow.com/q/23803743/1048572?What-is-the-promise-construction-antipattern-and-how-to-avoid-it)! – Bergi Mar 31 '18 at 10:23
  • 1
    Thank you for antipattern warning - after refactoring I go achieved better code what looks exactly like Sajeetharan answer – bensiu Mar 31 '18 at 19:14