Javascript Firebase:在断开internet连接时使用Localstorage进行渲染
这是我创建的一个函数,用于检查在应用程序运行期间是否断开了internet连接Javascript Firebase:在断开internet连接时使用Localstorage进行渲染,javascript,firebase-realtime-database,ecmascript-6,Javascript,Firebase Realtime Database,Ecmascript 6,这是我创建的一个函数,用于检查在应用程序运行期间是否断开了internet连接 checkConnectionStatus () { firebase.database().ref().child('.info/connected').once('value').then((connectedSnap) => { if (connectedSnap.val() === true) { console.log('connected') t
checkConnectionStatus () {
firebase.database().ref().child('.info/connected').once('value').then((connectedSnap) => {
if (connectedSnap.val() === true) {
console.log('connected')
this.connectionStatus = true
} else {
console.log('disconnected')
this.connectionStatus = false
}
return connectedSnap
})
}
我在另一个类中使用了这个函数,如下所示,但是连接状态没有正确更新
async update () {
let tempCollection = null
await this.firebaseService.checkConnectionStatus()
if (this.firebaseService.connectionStatus) {
tempCollection = await this.firebaseService.getTodoListAsCollection()
} else if (!this.firebaseService.connectionStatus) {
tempCollection = this.localStorage.getTodoList()
}
.///
}
您不会从
checkConnectionStatus
函数返回任何内容<代码>异步/等待
需要承诺
才能正常工作。看
所以类似这样的东西应该更接近:
checkConnectionStatus () {
return new Promise(resolve => {
firebase.database().ref().child('.info/connected').once('value').then((connectedSnap) => {
if (connectedSnap.val() === true) {
console.log('connected')
this.connectionStatus = true
} else {
console.log('disconnected')
this.connectionStatus = false
}
resolve();
})
}
更简单的版本可以是:
checkConnectionStatus () {
return new Promise(resolve => {
firebase.database().ref().child('.info/connected').once('value').then((connectedSnap) => {
resolve(connectedSnap.val())
})
}
}
然后将其用作:
let tempCollection = null
let connectionStatus = await this.firebaseService.checkConnectionStatus()
if (connectionStatus) {
tempCollection = await this.firebaseService.getTodoListAsCollection()
} else if (!connectionStatus) {
tempCollection = this.localStorage.getTodoList()
}
或者您可以完全不使用helper函数,因为once()
已经返回一个承诺:
let tempCollection = null
let snapshot = await firebase.database().ref().child('.info/connected').once('value')
let connectionStatus = snapshot.val()
if (connectionStatus) {
tempCollection = await this.firebaseService.getTodoListAsCollection()
} else if (!connectionStatus) {
tempCollection = this.localStorage.getTodoList()
}
我很难理解这个问题。这听起来有点像一个故事。你能不能展示一段代码,它不能按照你期望的方式工作?很抱歉给你带来不便,我已经更新了我的帖子。你能检查一下吗?我们能不能用on()来代替一次?因为当互联网连接时,我需要连接状态为真。