我有这个函数,我在typescript和nativescript中写入count的值从sqlite返回为promise但不可访问因此函数总是返回false
checkIfBookmarkAlreadyExist(study_number:string){
this.countInDb=0;
(new Sqlite("sts.db")).then(db => {
this.countInDb=db.get("SELECT count(*) FROM bookmarks WHERE study_number= ?",[study_number] ).then(row => {
return row;
});
});
console.log("value of countInDb ouside: ", this.countInDb);
if(this.countInDb>1){
return true
}else{
return false;
}
}
答案 0 :(得分:0)
也许你可以试试:
让它'NESTED'功能:
checkIfBookmarkAlreadyExist(study_number:string){
this.countInDb=0;
let flag = true;//I don't recommend to make this variable global
(new Sqlite("sts.db")).then(db => {
db.get("SELECT count(*) FROM bookmarks WHERE study_number= ?",[study_number] )
.then(row => {
this.countInDb= row;
console.log("value of countInDb ouside: ", this.countInDb);
if(this.countInDb>1){
return true
} else{
return false;
}
});
});
}
尝试异步
if(checkIfBookmarkAlreadyExist(study_number)>1){
return true
}else{
return false;
}
async function checkIfBookmarkAlreadyExist(study_number:string) {
this.countInDb = 0;
try {
this.countInDb = await getData(study_number);
console.log("value of countInDb ouside: ", this.countInDb);
} catch (e) {
console.error(e);
}
return this.countInDb;
}
function getData(study_number:string) {
(new Sqlite("sts.db")).then(db => {
this.countInDb=db.get("SELECT count(*) FROM bookmarks WHERE study_number= ?",[study_number] )
.then(row => {
return row;
});
});
}