Get jaydata to return objects synchronously

523 Views Asked by At

I have methods to Set and Get data from WEBSql scattered across my javascript. Here's my "get" function to fetch data using jayData :

function getProductRow(key){

    console.debug("Product key.. " + key);

    $data("Product")
        .query("it.Key == productKey", { productKey: key})
        .then(function(items) {
            items.forEach(function(item) {
               console.debug("item.value.. " + item.Value);
               return item.Value;
            });
         });    
}

And here's my js method which is called from various places, and which inturn, calls the getProductRow method:

function getProdValue(key) {
    console.debug("called getProdValue with " + key);

    var value = getProdRow(key);
    var prod = $.parseJSON(value);          
    // do stuff with prod       

}

The logs i see on my console are :

called getProdValue with abc111
Product key.. abc111
Uncaught SyntaxError: Unexpected token u
item.value.. // some stringified valid json string

Obviously, due to the asynchronous nature of jaydata, the control is returned to the calling function before the item.Value is retrieved, and parsing "undefined" gives me the syntax error. How can i make the whole call synchronous, so that control goes back to calling function only when item.Value is returned?

1

There are 1 best solutions below

3
On

You can not make it sync. From your code I guess that you read by primary key, so you'll need something like:

function getProdValue(key) {
       $data("Product").read(key)
       .then(function(product) {
            return $.parseJSON(product.value);
        });
 }