0

我想在打字稿中编写一个RethinkDB通用库。 我看到RethinkDB的javascript返回promise,我想,例如在GetAll方法中,返回数组项。目前我写了这样的事情:RethinkDB在打字稿中的通用库,从方法返回承诺结果

public GetAll(): T[] { 
    this.db.GetConnection().then(connection => { 
     this.db.GetTable(this.tableName).run(connection).then(cursor => { 
      cursor.toArray<T>().then(items => { 
       return items; 
      }); 
     }); 
    }); 
} 

但我在T []第一线得到一个错误:一个函数声明类型既不是“无效”,也没有“任意”必须返回一个值。

如何从这个方法返回一个T数组?

回答

0

因为你需要返回的结果是从Promise未来(即异步返回),你的方法也需要返回一个Promise

public GetAll(): Promise<T[]> { 
    return this.db.GetConnection().then(connection => { 
     return this.db.GetTable(this.tableName).run(connection).then(cursor => { 
      return cursor.toArray<T>(); 
     }); 
    }); 
} 

这句法可以提高使用打字稿的异步很多/等待支持:

public async GetAll(): Promise<T[]> { 
    let connection = await this.db.GetConnection(); 
    let table = this.db.GetTable(this.tableName); 
    let cursor = table.run(connection); 
    return await cursor.toArray<T>(); 
}