【问题标题】:PouchDb data not updating on Get requestPouchDb 数据未在获取请求时更新
【发布时间】:2016-08-21 17:06:24
【问题描述】:

您好,我已尝试从 pouch db 本地数据库中获取数据。

这是我的代码。

function test(){

var jsondata;

var deviceId = localStorage.getItem("deviceId");    

localDB.get(deviceId).then(function(doc){                 

  jsondata = doc.data;

});
return jsondata}

test();

在这里,我可以在 get 函数中获取控制台数据,但从最后一行开始,我得到了未定义。

【问题讨论】:

    标签: javascript jquery pouchdb


    【解决方案1】:

    函数内部的部分在promise解决后执行。

    末尾的console.loglocalDB.get 语句之后立即执行。此时,promise 尚未解决,回调尚未执行,因此 jsondata 的值尚未设置 - 将 undefined 保留为 jsondata 的值

    编辑 1:

    var jsondata;
    
    var deviceId = localStorage.getItem("deviceId");    
    
    localDB.get(deviceId).then(function(doc){                 
    
      jsondata = doc.data;
      console.log(jsondata)
    
      // whatever you want to do with `jsondata`,
      // do it here
    });
    
    // not here
    

    编辑 2:

    如果要将此代码放在函数中,则应返回 Promise 本身。所以你的代码变成这样:

    function getDoc(){
    
        var deviceId = localStorage.getItem("deviceId");    
    
        return localDB.get(deviceId);
    }
    

    现在在代码中需要使用 jsondata 的地方使用 .then() 解决此承诺

    .
    .
    getDoc().then(function(doc){
        // your code that needs to use the document
    });
    .
    .
    

    【讨论】:

    • 无论你想对检索到的文档做什么,都应该在回调中完成。
    • 对不起,库尔是新来的。你能把这个代码sn-p发给我吗
    • 那部分我可以理解,如果我在函数中使用,我怎么能返回值。 (我已经编辑了我的问题)
    • 你是说这段代码在需要返回解析值的函数中?
    • 是的,正是库尔。请帮我解决这个问题
    猜你喜欢
    • 2019-09-30
    • 2019-02-10
    • 1970-01-01
    • 2020-10-14
    • 1970-01-01
    • 1970-01-01
    • 2020-04-01
    • 2021-10-21
    • 2020-12-31
    相关资源
    最近更新 更多