Reputation: 155
I need to open transaction, read objectstore data and check if data is not undefined and if data is defined at indexedDB use it or if not fetch new data using network_ip() function.
But problem is that when i use Promises, the "const r" variable is always undefined with resolve(e.target.result).
without resolve the "r" variable is defined successfully, but the result is empty.
const time = new Date().getTime();
async function network_ip(){
let ipaddr = await fetch('https://example.com/ip.php');
ipaddr = await ipaddr.text();
db.transaction(['ip'], 'readwrite').objectStore('ip').put({ip:ipaddr, times:time}, 1);
}
new Promise(function(resolve) {
db.transaction(['ip'], 'readwrite').objectStore('ip').get(1).onsuccess = function(e){
const r = resolve(e.target.result); // this line is not working
if (r !== undefined && r.ip !== undefined && r.times !== undefined) {
t = r.times;
i = r.ip;
}else{
network_ip();
}
}
}).then(function(result){
console.log(result);
});
Upvotes: 0
Views: 266
Reputation: 1511
I believe that you want r
to be assigned the value of e.target.result
and also have e.target.result
passed to the resolve()
function.
What you have doesn't work because resolve()
doesn't have a return value, so assigning anything to its execution will be undefined. But all you need is to make it into 2 lines:
resolve(e.target.result);
const r = e.target.result;
Upvotes: 1