问题描述
大家下午好,
我的问题与 javascript 相关,我创建了一个名为 checkflights 的函数、一系列用于打开 indexeddb 数据库的语句和一个触发 checkflights 的 window.onload。
似乎 window.onload 在打开数据库语句之前触发,因此 checkflights 函数无法正常运行,因为 db 被认为是 null。
impl CustomTrait<u64> for std::ops::Range<u64> {}
解决方法
您正在通过再次使用 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 不返回承诺,但您可以自己围绕顶部编写一个异步/等待包装器,或者考虑使用像 https://github.com/jakearchibald/idb 这样的库来保证 indexedDB。