我知道如何使用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!执行时将引发错误。

最佳答案

您可以使用不需要可选值的方式构造代码,如下所示:

  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

09-25 16:20