Anandhakumar R Anandhakumar R - 3 months ago 22
jQuery Question

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.

Kul Kul
Answer

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