简体   繁体   中英

PouchDb data not updating on Get request

Hi I have tried to fetching the data from pouch db local database.

Here my code.

function test(){

var jsondata;

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

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

  jsondata = doc.data;

});
return jsondata}

test();

Here I can get the console data inside get function but from the last line I was getting undefined.

The part inside the function is executed after the promise is resolved.

The console.log at the end is executed immediately after the localDB.get statement. At this point, the promise hasn't been resolved, the callback hasn't been executed and hence the value of jsondata hasn't been set - leaving undefined as the value of jsondata

Edit 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

Edit 2:

If this code is to be placed in a function, you should return the promise itself. So your code becomes something like:

function getDoc(){

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

    return localDB.get(deviceId);
}

Now resolve this promise using .then() in that place in your code where you need to use jsondata

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM