我想访问从nativescript sqlite返回的值

时间:2018-04-15 16:00:55

标签: javascript typescript nativescript angular2-nativescript

我有这个函数,我在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;
        }

    }

1 个答案:

答案 0 :(得分:0)

也许你可以试试:

  1. 让它'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;
                    }
                });
            });  
    }
    
  2. 尝试异步

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