Búsqueda de sitios web

typescript - Cómo declarar el retorno de una Promise de un array de objetos de cualquier tipo


Intento definir el retorno del método que devolvería una Promesa de un arreglo de objetos:

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

sin embargo, me estoy enfrentando al error "[ts] Una función cuyo tipo declarado no es 'void' ni 'any' debe devolver un valor."

¿Qué estoy haciendo mal?

Respuesta #1

Como dice el error, tu función readAll espera un retorno de tipo Promise<any[]>. Intenta retornar la Promise dentro del 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();
    });

}

Respuesta #2

La sugerencia de Andrii Nikolaienko llevó a una solución funcional:

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

Gracias por la sugerencia.