首页 > 解决方案 > window.onload 在索引数据库语句之前开始

问题描述

大家下午好

我的问题与 javascript 相关,我创建了一个名为 checkflights 的函数、一系列打开 indexeddb 数据库的语句和一个触发 checkflights 的 window.onload。

似乎 window.onload 在打开数据库语句之前触发,因此 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")
                }
        }
    }

标签: javascriptindexeddbonload

解决方案


您正在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 在上面的评论中所建议的那样,您可能需要等待请求被处理。IndexedDB 不返回承诺,但您可以自己在顶部编写一个 async/await 包装器,或者考虑使用像https://github.com/jakearchibald/idb这样的库来 Promisify indexedDB。


推荐阅读