【问题标题】:Javascript Closure and WebRTC callback issuesJavascript 关闭和 WebRTC 回调问题
【发布时间】:2016-02-10 09:23:31
【问题描述】:

我遇到了这个问题,我正在创建一个闭包并单步执行调试器,变量connectingClientId 在闭包回调(localOfferCreated)中正确设置。当 createOffer 调用回调时,connectedClientId 未定义。怎么会是这种情况?整晚都在用头撞墙。

function publishStream(handShakeInitiator, connectingClientId) {
    var localOfferCreated = offerClosure(connectingClientId);
    var localIceCandidate = iceClosure(connectingClientId);
    peerConnections[connectingClientId] = new RTCPeerConnection(peerConnectionConfig);
    peerConnections[connectingClientId].onicecandidate = localIceCandidate;

    peerConnections[connectingClientId].addStream(localStream);

    if (handShakeInitiator) {
        peerConnections[connectingClientId].createOffer(localOfferCreated, createOfferError, offerOptions);
    }
}

function offerClosure(id) {

    var connectingClientId = id;

    function offerCreated(description) {
        peerConnections[connectingClientId].setLocalDescription(description, function (connectingClientId) {
            webSocket.send(JSON.stringify({
                'control': signalConstants.sendToClient,
                'cid': connectingClientId,
                'sdp': description
            }));
        }, function () {
            console.log('Error setting description.');
        });
    };

    return offerCreated;
}

从调试器中注意这些:

connectingClientId 已设置 -

connectingClientId 在调用时未设置 -

我在这里错过了什么?

【问题讨论】:

    标签: javascript callback closures webrtc


    【解决方案1】:

    来自RTCPeerConnection.setLocalDescription

    successCallback
    是一个没有参数的函数,将被调用 当描述已成功设置时。此时,可以 将报价发送到可以将其转发到远程服务器的远程服务器 客户

    您通过将connectingClientID 作为内部函数参数来重新定义它。请记住,命名函数参数是一个隐式变量声明,正如文档所说,它将未定义,因为成功回调不提供任何参数。 JavaScript 函数可以访问它们的外部作用域,所以你的匿名函数不需要传递这个参数,它可以简单地引用它来创建一个闭包。

    function offerCreated(description) {
        peerConnections[connectingClientId].setLocalDescription(description, function() {  
            webSocket.send(JSON.stringify({
                control: signalConstants.sendToClient,
                cid: connectingClientId,
                sdp: description
            }));
        }, function () {
            console.log('Error setting description.');
        });
    };
    

    【讨论】:

    • 添加了我的半途而废的答案,希望你不介意。
    • 感谢您的帮助。男人男人男人,有时会忽略一些小事。
    猜你喜欢
    • 2016-10-16
    • 2020-08-26
    • 1970-01-01
    • 1970-01-01
    • 2016-02-09
    • 1970-01-01
    • 1970-01-01
    • 2012-08-04
    • 1970-01-01
    相关资源
    最近更新 更多