[英]PouchDb data not updating on Get request
Hi I have tried to fetching the data from pouch db local database. 嗨,我已经尝试从pouch db本地数据库中获取数据。
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. 在这里,我可以在get函数中获取控制台数据,但是从最后一行开始,我是未定义的。
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. 最后的console.log
在localDB.get
语句之后立即执行。 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
至此,promise尚未解决,回调尚未执行,因此尚未设置jsondata
的值- undefined
为jsondata
的值
Edit 1: 编辑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: 编辑2:
If this code is to be placed in a function, you should return the promise itself. 如果将此代码放置在函数中,则应返回promise本身。 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
现在.then()
在您需要使用jsondata
代码中的那个位置使用jsondata
.then()
解决此承诺
.
.
getDoc().then(function(doc){
// your code that needs to use the document
});
.
.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.