window.onload在索引db语句之前启动

jm81lzqq  于 2021-09-13  发布在  Java
关注(0)|答案(1)|浏览(317)

大家下午好,
我的问题与javascript有关,我制作了一个名为checkflights的函数,一系列用于打开indexeddb数据库的语句和一个触发checkflights的window.onload。
似乎window.onload在open数据库语句之前触发,因此checkflights函数不能正常运行,因为db被认为是空的。
有解决办法吗?代码如下。提前感谢您的支持。

var db = null
    const request = indexedDB.open('MyDataBase', '1')

    //on upgrade needed
    request.onupgradeneeded = e => {
        var db = e.target.result
        /* note = {
            title: "note1",
            text: "this is a note"
        }*/
        const myFlights = db.createObjectStore("my_flight", {
            keyPath: "flightid"
        })

    }

    request.onsuccess = e => {
        var db = e.target.result 

    }

    request.onerror = e => {
        alert(`error: ${e.target.error} was found `)
    }    

window.onload = function () {
        checkFlights()

    }

function checkFlights() {
        const tx = db.transaction("my_flight", "readonly");
        // var objectStore = transaction.objectStore('my_flight');
        const mesVols=tx.objectStore("my_flight")

        var countRequest = mesVols.count();
        countRequest.onsuccess = function() {
            console.log(countRequest.result);
            if(countRequest.result>0 && window.navigator.onLine){
                sendFlights()
                notify("Flights sent to server")
                }
        }
    }
kt06eoxx

kt06eoxx1#

你在重新澄清 db 从外部范围,通过使用 var 再一次。使用时 var 在局部作用域中,您不会从外部作用域影响变量,而是实际创建新的局部作用域 db 变量

var db = null
    const request = indexedDB.open('MyDataBase', '1');
    //on upgrade needed
    request.onupgradeneeded = e => {
         db = e.target.result
        /* note = {
            title: "note1",
            text: "this is a note"
        }*/
        const myFlights = db.createObjectStore("my_flight", {
            keyPath: "flightid"
        })

    }

    request.onsuccess = e => {
         db = e.target.result 

    }

    request.onerror = e => {
        alert(`error: ${e.target.error} was found `)
    }    

window.onload = function () {
        checkFlights()

    }

function checkFlights() {
        const tx = db.transaction("my_flight", "readonly");
        // var objectStore = transaction.objectStore('my_flight');
        const mesVols=tx.objectStore("my_flight")

        var countRequest = mesVols.count();
        countRequest.onsuccess = function() {
            console.log(countRequest.result);
            if(countRequest.result>0 && window.navigator.onLine){
                sendFlights()
                notify("Flights sent to server")
                }
        }
    }

正如@kinglish在上面的评论中所建议的,您可能需要等待请求得到处理。索引XDB不返回一个约定,但是您可以自己在顶部写一个异步/等待 Package ,或者考虑使用一个类似的库。https://github.com/jakearchibald/idb 这将预示着indexeddb。

相关问题