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