Search code examples
angulartypescriptpromiseionic2cordova-plugins

Promise<any> chaining in Ionic2 SQLite native plugin


I am new to Javascript promises, and I am not being able to do a proper chaining.

I am using the native SQLite Ionic2 plugin that wraps the cordova sqlite plugin in a promise-like API. I want to wait for an SQL query to resolve and then use the result set to get the data, since I am executing a SELECT clause. The SQLite example, along with my code, is as follows:

  [...]
  executeQuery(query: string, params: any){
    let db = new SQLite();
    return db.openDatabase({
      name: 'applicationData.db',
      location: 'default'
    }).then(() => {
      db.executeSql(query, params).then((resultSet) => {
        return resultSet;
      }, (err) => {
        console.error('Unable to execute sql: ', err);
      });
    }, (err) =>{
      console.error('Unable to open database: ', err);
    });
  }
    
  getConfig(){
    let query = 'SELECT * from configuration';
    this.executeQuery(query, []).then((resultSet) => {
      resultSet.rows.item(0);
    }, (err) => {
    
    });
  }
  [...]

And I am getting:

Property 'rows' does not exist on type 'void'.

[19:13:19] transpile failed

[19:13:19] ionic-app-script task: "build"

[19:13:19] Error: Error

L23:  this.executeQuery(query, []).then((resultSet) => {
L24:    resultSet.rows.item(0);
L25:  }, (err) => {

Solution

  • You need to return the db.executeSql call inside your executeQuery method, otherwise your Promise just returns void like the transpiler says:

    executeQuery(query: string, params: any){
        let db = new SQLite();
        return db.openDatabase({
            name: 'applicationData.db',
            location: 'default'
        }).then(() => {
            //here
            return db.executeSql(query, params).then((resultSet) => {
                return resultSet;
            }, (err) => {
                console.error('Unable to execute sql: ', err);
            });
        }, (err) =>{
            console.error('Unable to open database: ', err);
       });
    }