0

I have been trying alot to assign var to result without luck

self.addProductToCart = function (data, event) {

    var theproduct = db.pos_products.get({id: data.idProduct}).then(function (pos_product) {
                        // console.log(pos_product.value); // returning results, which indicates it is working
                        return pos_product.value
                }).catch(function(error) {
                    console.log ("Ooops: " + error);
                });
                
                
     console.log (theproduct); // retunrning no results   only    DexiePromise { listeners: Arrar(0), _lib.....

}

also i tried with


    async function myfunction(idProduct) {
        let result = await db.pos_products.get({id: idProduct}).then(function (pos_product) {
                return pos_product.value
        }).catch(function(error) {
            console.log ("Ooops: " + error);
        });
    }
    
    
    self.addProductToCart = function (data, event) {

        var theproduct = myfunction(data.idProduct);
            console.log ('theproduct');
            console.log (theproduct); // retunrning PromiseĀ {<pending>}
    }

i hope someone can help. i need the variable theproduct to be used later inside current

inventor
  • 55
  • 2
  • 3
  • 10

2 Answers2

-1

I am not sure why your code does not work, but I often see beginner programmers not knowing how to use async/await and promises, here for example you awaited the dexie call and then had a .then after it, which i am pretty sure dont play along so well? But anyway, the code below should work, just check for the dexie documentation, these simple queries are described there beautifully.

const pos_products = await db.pos_products.get({id: idProduct});
console.log(pos_products.value);
//OR
const { value: pos_products } = await db.pos_products.get({id: idProduct});
console.log(pos_products);
Komi
  • 450
  • 5
  • 14
-1

i resolved the issue by adding async to self.addProductToCart = async function

    async function myfunction(idProduct) {
        var pos_product = await db.pos_products.get({id: idProduct});
        return pos_product.value;
    }

self.addProductToCart = async function (data, event) {
        var pos_product = await myfunction(data.idProduct);
        console.log(pos_product);
}
inventor
  • 55
  • 2
  • 3
  • 10