javascript - 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")
}
}
}
解决方案
您正在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。
推荐阅读
- android - 为什么布尔 DBHelper.updateStudents(java.lang.String,java.lang.String,java.lang.String,java.lang.String, java.lang.String) on nullobjectreference
- arrays - 直接从 msi 位置路径和 for 循环中卸载时出现问题
- angular - 我的属性在 .ts 文件中未定义但 .html 文件有效的原因是什么
- symfony - 在 Symfony 4.4 中使用 RedisTagAwareAdapter
- android - 来自 SpaceX REST API 的数据未显示
- python - 当远程模块具有 pytest_collection_modifyitems() 时,Pytest-xdist 抛出 AssertionError
- security - 从过去 20 天开始,我不断受到 DDoS 攻击
- java - 限制每分钟 JWT 令牌的数量
- nginx - 用于通过 url 播放 .ogg 音频的 Nginx 配置
- reactjs - 如何在材质 UI 中的深色和浅色主题之间为 Paper 组件交换 2 种不同的背景颜色?