代码之家  ›  专栏  ›  技术社区  ›  cHorse

无法让CoffeeScript识别js文件中的函数

  •  -2
  • cHorse  · 技术社区  · 8 年前

    我正在用Coffeescript编写一个简单的应用程序来控制飞利浦的色光。我已经包括 this module 进入我的项目。下面的代码似乎运行良好,直到我尝试使用 setLightState . 编译器说函数不是函数。我不太明白为什么它不能识别这个功能。

    # Connect with Philips Hue bridge
    jsHue = require 'jshue'
    hue = jsHue()
    
    # Get the IP address of any bridges on the network
    hueBridgeIPAddress = hue.discover().then((bridges) => 
        if bridges.length is 0
            console.log 'No bridges found. :('
        else 
            (b.internalipaddress for b in bridges)
    ).catch((e) => console.log 'Error finding bridges', e)
    
    if hueBridgeIPAddress.length isnt 0 # if there is at least 1 bridge
        bridge = hue.bridge(hueBridgeIPAddress[0])  #get the first bridge in the list
    
        # Create a user on that bridge (may need to press the reset button on the bridge before starting the tech buck)
        user = bridge.createUser('myApp#testdevice').then((data) =>
            username = data[0].success.username
            console.log 'New username:', username
            bridge.user(username)
        )
    
        if user?
            #assuming a user was sucessfully created set the lighting to white
            user.setLightState(1, {on:true, sat:0, bri:100, hue:65280}).then((data) =>
                # process response data, do other things
            )
    
    1 回复  |  直到 8 年前
        1
  •  0
  •   Alexander Presber    8 年前

    正如您在 github page of the jshue lib , bridge.createUser 直接返回a user 对象

    相反,示例代码设置 使用者 变量 在…内 这个 then 返回的函数 promise :

    bridge.createUser('myApp#testdevice').then(data => {
        // extract bridge-generated username from returned data
        var username = data[0].success.username;
    
        // instantiate user object with username
        var user = bridge.user(username);
        user.setLightState( .... )
    });
    

    可以预期,使用这种方法 使用者 变量将正确设置,并且 user.setLightState 将定义。

    一个独立的示例:

    this Codepen 例如:

    url = "https://api.ipify.org?format=json"
    
    outside = axios.get(url).then (response) =>
      inside = response.data.ip
      console.log "inside: #{inside}"
      inside
    
    console.log "outside: #{outside}"
    

    控制台输出为

    outside: [object Promise]
    inside: 178.19.212.102
    

    您可以看到:

    1. 这个 outside 日志是 第一 是一个 Promise 对象
    2. 这个 inside 日志来了 最后的 并包含来自Ajax调用的实际对象(在本例中是您的IP)
    3. 这个 然后 函数隐式返回 在…内 不会改变任何事情
    推荐文章