【问题标题】:Dexie how to assign a result to a variable? [duplicate]Dexie如何将结果分配给变量? [复制]
【发布时间】:2021-08-11 08:30:21
【问题描述】:

我一直在尝试将 var 分配给 result 却没有运气

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

}

我也试过


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

我希望有人可以提供帮助。我需要变量 theproduct 稍后在 current 中使用

【问题讨论】:

    标签: javascript dexie


    【解决方案1】:

    我不确定您的代码为什么不起作用,但我经常看到初学者程序员不知道如何使用 async/await 和 promises,例如,您等待 dexie 调用,然后在它之后有一个 .then,我我很确定不要玩得这么好? 不过不管怎样,下面的代码应该可以工作,去看看 dexie 文档,这些简单的查询在那里描述得很漂亮。

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

    【讨论】:

      【解决方案2】:

      我通过将 async 添加到 self.addProductToCart = async 函数解决了这个问题

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

      【讨论】:

        猜你喜欢
        • 2020-12-01
        • 2011-08-27
        • 1970-01-01
        • 2010-10-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-02-04
        • 1970-01-01
        相关资源
        最近更新 更多