scottohara / tvmanager

PWA for tracking recorded, watched & upcoming TV shows
MIT License
3 stars 0 forks source link

Switch to async/await instead of callbacks #85

Closed scottohara closed 4 years ago

scottohara commented 5 years ago

The WebSQL async API predates native ES2015 promises (or ES2017 async/await) ; so it uses callbacks, e.g.

db.readTransaction(
  tx => tx.executeSQL(
    sql,
    [params],
    execSuccessCallback,
    execErrorCallback
  ),
  txErrorCallback
);

The models extend the same callback-style, e.g.

Program.list(callback);
Program.find(id, callback);
Program.count(callback);
Program.removeAll(callback);
Program.save(callback);

These model methods should instead return a promise that wraps the db API calls, so that we can use async/await in any calling code (controllers), e.g.

class Program extends Base {
  ...

  public static count(): Promise<Number> {
    return new Promise((resolve, reject) => {
      this.db.readTransaction((tx: SQLTransaction): void => tx.executeSql(
        "SELECT  COUNT(*) AS ProgramCount FROM Program", [],
        (_: SQLTransaction, resultSet: SQLResultSet): void => resolve(resultSet.rows.item(0).ProgramCount,
    (): boolean => reject(0)
      );
    });
  }
}

// Somewhere else...
async someFunc() {
  const count = await Program.count();
  // do something with count
}