I am using Ionic 2 with SQLite. I am getting an error, and I suspect it is due to me not using Promises correctly.
I get the following error:
ERROR REFRESHING CHATS: {}
TypeError {stack: (...), message: "Cannot read property 'executeSql' of undefined"}
ts
private database = new SQLite();
public openDatabase(): Promise<Array<Message>> {
let promise: Promise<Array<Message>> = new Promise<Array<Message>>(resolve => {
if (this.database) {
let promiseChats: Promise<any> = this.refreshChats();
let promiseMessages: Promise<any> = this.refreshMessages();
Promise.all([promiseChats, promiseMessages]).then(() => { resolve(this.messages) });
} else {
this.database.openDatabase({
name: "data.db",
location: "default"
}).then(() => {
let promiseChats: Promise<any> = this.refreshChats();
let promiseMessages: Promise<any> = this.refreshMessages();
Promise.all([promiseChats, promiseMessages]).then(() => { resolve(this.messages) });
}, (error) => {
console.log("OPEN ERROR: ", error);
});
}
});
return promise;
}
public refreshChats(): Promise<any> {
return this.database.executeSql("SELECT * FROM chats", [])
.then((chatData) => {
this.chats = [];
if (chatData.rows.length > 0) {
for (var i = 0; i < chatData.rows.length; i++) {
this.populateChat(chatData, i);
}
}
return this.chats;
})
.catch(error => {
console.log("ERROR REFRESHING CHATS: " + JSON.stringify(error));
console.log(error);
});
}
When I debug the code, and break on this.database.executeSql
, this.database
is not undefined
. Also, you can see there is a check on this.database
to see if it's undefined
before too. Yet, the debugger steps out the Promise
into the error
, reporting the error shown.
Also, after the Promise
finishes, the this.chats
are populated. So I am very confused.
If anyone can suggest what I am doing incorrectly, I would appreciate it.
UPDATE
I have updated the code as follows, but still get the same error:
public openDatabase(): Promise<Array<Message>> {
let promise: Promise<Array<Message>> = new Promise<Array<Message>>(resolve => {
if (this.database) {
Promise.all([this.refreshChats(), this.refreshMessages()]).then(() => { resolve(this.messages) });
} else {
this.database.openDatabase({
name: "data.db",
location: "default"
}).then(() => {
Promise.all([this.refreshChats(), this.refreshMessages()]).then(() => { resolve(this.messages) });
}, (error) => {
console.log("OPEN ERROR: ", error);
});
}
});
return promise;
}
public refreshChats(): Promise<any> {
return this.database.executeSql("SELECT * FROM chats", [])
.then((chatData) => {
let promises: Array<any> = [];
this.chats = [];
if (chatData.rows.length > 0) {
for (var i = 0; i < chatData.rows.length; i++) {
promises.push(this.populateChat(chatData.rows.item(i)));
}
}
Promise.all(promises).then(() => {
return this.chats;
});
})
.catch(error => {
console.log("ERROR REFRESHING CHATS: " + JSON.stringify(error));
console.log(error);
});
}