大家下午好,
我的问题与javascript有关,我做了一个名为checkflights的函数,一系列打开indexeddb数据库的语句,以及一个触发checkflight的window.onload。
window.onload似乎在打开数据库语句之前触发,因此checkflights函数不能正常运行,因为数据库被认为是null。
有什么解决方案吗?下面的代码。提前感谢您的支持。
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")
}
}
}
您正在通过再次使用var
从外部范围重新定义db
。在本地作用域中使用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不返回promise,但您可以围绕顶部编写一个async/await包装,或者考虑使用类似https://github.com/jakearchibald/idb将Promisify indexedDB。