-1

I am new to javascript promises, I am using below code from NativeScript to query sqlite database and just want to return true if row exists and false otherwise:

function hasBookmark(url) {
    (new Sqlite("pakjobs.db")).then(db => {
        db.all("SELECT url FROM bookmarks WHERE url=?", [url]).then(rows => {
            return rows.length ? true : false;
        }, error => {
            console.log("hasBookmark ERROR", error);
            return false;
        });
    }, error => {
        console.log("hasBookmark ERROR", error);
        return false;
    });

    return false;
}

However function ALWAYS returns false.

Can anybody tell how do I return true if row exists and false otherwise ?

Thanks for the help

Dave Newton
  • 158,873
  • 26
  • 254
  • 302
dev02
  • 1,776
  • 3
  • 24
  • 45
  • 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) – ASDFGerte Aug 25 '18 at 17:24

2 Answers2

2

You are not going to be able to return true or false, that's pretty much the point of Promises, you can't return something asynchronously in javascript.

What you can do, however, is directly returning the Promise you're creating and then calling .then on it.

function hasBookmark(url) {
    return (new Sqlite("pakjobs.db")).then(db => {
        return db.all("SELECT url FROM bookmarks WHERE url=?", [url]).then(rows => {
            return rows.length ? true : false;
        }, error => {
            console.log("hasBookmark ERROR", error);
            return false;
        });
    }, error => {
        console.log("hasBookmark ERROR", error);
        return false;
    });

}

const hasBookmarkPromise = hasBookmark('someurl');

hasBookmarPromise.then(value => {
    if (value === true) {
        console.log('has bookmarks');
    }
});
Axnyff
  • 9,213
  • 4
  • 33
  • 37
-2
function hasBookmark(url) {
    return new Promise((resolve, reject) => {
        (new Sqlite("pakjobs.db")).then(db => {
            db.all("SELECT url FROM          bookmarks WHERE url=?", [url]).then(rows => {
                resolve(rows.length ? true : false)
            }, error => {
                console.log("hasBookmark ERROR", error);
                resolve(false);
            });
        }, error => {
            console.log("hasBookmark ERROR", error);
            resolve(false);
        });
    });
}

hasBookmark(url).then(function(isValid){
   If(isValid){
     // Do something
   }
});
dev02
  • 1,776
  • 3
  • 24
  • 45
  • Apologies, was trying from iphone 5s , a bit difficult to do formatting from phones , but yeah have edited the answer. – Krishna Satwaji Khandagale Aug 25 '18 at 16:59
  • 2
    Avoid the [`Promise` constructor antipattern](https://stackoverflow.com/q/23803743/1048572?What-is-the-promise-construction-antipattern-and-how-to-avoid-it)! – Bergi Aug 25 '18 at 17:09