-2

我正在 Coffeescript 中编写一个简单的应用程序来控制飞利浦 Hue 灯。我已将此模块包含在我的项目中。下面的代码似乎可以正常工作,直到我尝试使用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
        )
4

1 回答 1

0

正如您在 jshue lib 的 github 页面上看到的那样,bridge.createUser直接返回user对象。

相反,示例代码在返回的promise的函数user设置了变量:then

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变量将被正确设置并被user.setLightState定义。

一个独立的例子:

这个 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. then隐式返回的函数inside不会改变任何东西
于 2018-03-22T09:24:01.107 回答