我很难看到我的代码摘录。
_.forEach peerIds, (peerId) =>
console.log "connecting to peerId: #{ peerId }"
connection = peer.connect peerId
connection.on "error", (error) =>
alert error.type
connection.on "open", =>
console.log "connection to peerId #{ connection.peer } is open: #{ connection.open }"
@connections.push connection
@listenForMessage connection
这是我正在研究的p2p聊天的一部分。基本上它通过对等ID列表,为每个ID创建一个连接,并在它创建的每个连接上放置一个事件监听器。
您看到的变量_
是Lo-Dash。变量peer
为PeerJS。
如果我们假设peerIds
设置为["y", "z"]
,那么这是相当有趣的控制台输出:
peerIds:y,z
连接到peerId:y
连接到peerId:z
与peerId z的连接已打开:false
与peerId z的连接已打开:true
为什么使用属于对等open
的连接调用事件z
两次?我无法从内部循环中更改peerIds
,对吧?
我不知何故需要让这个运行同步(没有a)或者在异步时简单地纠正。
预期产出:
peerIds:y,z
连接到peerId:y
连接到peerId:z
与peerId的连接是打开的:true
与peerId z的连接已打开:true
答案 0 :(得分:1)
封闭!此外,CoffeeScript还为其提供了关键字do
。
_.forEach peerIds, (peerId) =>
connection = peer.connect peerId
do (connection) =>
connection.on "error", (error) ->
alert error.type
connection.on "open", =>
@connections.push connection
@listenForMessage connection