我知道如何在Swift中做到这一点,但对于Javascript作为初学者,我正在努力解决这个问题。让我们说这是我的功能:
const prom3 = Promise? //this is wrong, I know. Normally in Swift this is an optional
if (statement){
pickerActive = true
prom3 = pathToLottery.once("value", function(values) {
//some function
})
}
if (pickerActive == false){ //normally set to false
return
}else{
return prom3! //not working because this is Swift syntax. How do to this kind of Swift behavior in Javascript? Is it possible?
}
一种可能性是在主要内容中声明prom3,但我希望它能使它成为可选项。这可能吗?
这是应该的类型,也许有帮助:
const prom3: Promise<any> (if I put the function inside the main scoop and hovering my mouse over prom3)
声明没有问号的prom3和!执行时会抛出错误。
答案 0 :(得分:1)
您可以采用不需要可选值的方式构建代码,如下所示:
if (statement){
pickerActive = true
const prom3 = pathToLottery.once('value')
prom3.then(snap => {
// some func that has access to data at pathToLottery
const data = snap.val()
return
})
} else {
return
}
观看此视频以获取更多信息:https://www.youtube.com/watch?v=NgZIb6Uwpjc&t=35s