简体   繁体   中英

JavaScript Promise not resolving event.target.result

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

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;

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