1

i have this function that i wrote in typescript and nativescript the value for count is returned from sqlite as promise but not accessible so function alway returns 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;
        }

    }
pjoe
  • 43
  • 7
  • Possible duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – raul.vila Apr 15 '18 at 16:02
  • `countInDb` is set inside a callback which is executed after `console.log(... countInDb)` – raul.vila Apr 15 '18 at 16:03

1 Answers1

0

Maybe you can try:

  1. Make it 'NESTED' function:

    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. Try Async

    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;
                });
            });
    }
    
Ash
  • 131
  • 1
  • 4
  • this is not working the value is still false though the db return the value – pjoe Apr 16 '18 at 06:42
  • My fault. Try to take the `if(this.countInDb>1){ return true }else{ return false; }` out the async function. I modified the answer. – Ash Apr 16 '18 at 23:44