gpt4 book ai didi

firebase - 当一个函数需要前一个函数的值时,用于 Firebase 实时数据库查找的完成处理程序

转载 作者:行者123 更新时间:2023-12-04 03:30:23 25 4
gpt4 key购买 nike

我有以下获取时间表的代码

func fetchSchedule(completion: @escaping () -> ()) {

scheduleRef.queryOrderedByValue().queryEqual(toValue: true).observe(.value, with: { snapshot in

self.schedule = []

if snapshot.value is NSNull {
// Null

} else {

for child in snapshot.children {

if let snapshot = child as? DataSnapshot,

let schedule = Schedule(snapshot: snapshot) {

self.schedule.append(schedule)

}

}

}

})

}
上面得到了当前的时间表,但我不清楚的是我需要该值然后调用下一个函数调用,该函数调用在 SwiftUI View 的 .onAppear() 上获取该时间表的相关游戏
func getGames() {

scheduleStore.fetchSchedule()
//
gameStore.fetchGames(weekId: self.scheduleStore.schedule[0].weekId)

}
gameStore.fetchGames 总是返回 null,可能是因为它还没有完成 fetchSchedule 函数的处理?
如何确保第一个函数在调用 fetchGames 之前完成?

最佳答案

您在 fetchSchedule 的函数签名中内置了一个完成处理程序,但您没有使用它。

func fetchSchedule(completion: @escaping () -> ()) {

scheduleRef.queryOrderedByValue().queryEqual(toValue: true).observe(.value, with: { snapshot in

self.schedule = []

if snapshot.value is NSNull {
// Null

} else {

for child in snapshot.children {

if let snapshot = child as? DataSnapshot,

let schedule = Schedule(snapshot: snapshot) {

self.schedule.append(schedule)

}

}

completion() //<-- Here

}

})

}
然后,
func getGames() {
scheduleStore.fetchSchedule(completion: {
gameStore.fetchGames(weekId: self.scheduleStore.schedule[0].weekId)
})
}
您没有显示所有代码,但您在 self.schedule 中设置的 fetchSchedule 和发送到 self.scheduleStorefetchGames 之间可能也有一些问题 - 确保您只有一个地方存储数据-- 两个地方都应该是 self.schedule 吗?

更新,基于评论
此代码是近似的,因为我无权访问您的类型,但它应该可以帮助您入门:
func fetchSchedule(completion: @escaping ([Schedule]) -> ()) {

scheduleRef.queryOrderedByValue().queryEqual(toValue: true).observe(.value, with: { snapshot in

if snapshot.value is NSNull {
// Null

} else {

let schedules = snapshot.children.compactMap { child in
if let snapshot = child as? DataSnapshot, let schedule = Schedule(snapshot: snapshot) {
return schedule
}
return nil
}

completion(schedules)

}

})

}
func getGames() {
scheduleStore.fetchSchedule { schedules in
gameStore.fetchGames(weekId: schedules[0].weekId)
}
}

关于firebase - 当一个函数需要前一个函数的值时,用于 Firebase 实时数据库查找的完成处理程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66993752/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com