PouchDb 数据未根据 Get 请求更新
PouchDb data not updating on Get request
您好,我已尝试从 pouch db 本地数据库中获取数据。
这是我的代码。
function test(){
var jsondata;
var deviceId = localStorage.getItem("deviceId");
localDB.get(deviceId).then(function(doc){
jsondata = doc.data;
});
return jsondata}
test();
在这里,我可以在 get 函数中获取控制台数据,但从最后一行开始,我变得不确定。
函数内的部分在promise resolve后执行。
最后的console.log
在localDB.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:
如果要将此代码放在函数中,您应该 return 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
});
.
.
您好,我已尝试从 pouch db 本地数据库中获取数据。
这是我的代码。
function test(){
var jsondata;
var deviceId = localStorage.getItem("deviceId");
localDB.get(deviceId).then(function(doc){
jsondata = doc.data;
});
return jsondata}
test();
在这里,我可以在 get 函数中获取控制台数据,但从最后一行开始,我变得不确定。
函数内的部分在promise resolve后执行。
最后的console.log
在localDB.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:
如果要将此代码放在函数中,您应该 return 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
});
.
.