局部变量到全局javascript

局部变量到全局javascript,javascript,callback,stream,webrtc,kurento,Javascript,Callback,Stream,Webrtc,Kurento,我对JavaScript、webRTC和Kurento有问题。我自己解决不了这个问题。我试图将本地变量的远程流放入全局变量,但遇到了一些问题。我试图解释解决问题的所有步骤: 第一步,我有Kurento webRtcEndpoint函数: webRtcPeer = kurentoUtils.WebRtcPeer.startRecvOnly(videoElement, onPlayOffer, onError); 它调用函数“onPlayOffer”,即: 我已经编辑了函数processsPans

我对JavaScript、webRTC和Kurento有问题。我自己解决不了这个问题。我试图将本地变量的远程流放入全局变量,但遇到了一些问题。我试图解释解决问题的所有步骤: 第一步,我有Kurento webRtcEndpoint函数:

webRtcPeer = kurentoUtils.WebRtcPeer.startRecvOnly(videoElement, onPlayOffer, onError);
它调用函数“onPlayOffer”,即:

我已经编辑了函数processsPanswer,以以下方式获取流:

WebRtcPeer.prototype.processSdpAnswer = function(sdpAnswer, callbackEvent, successCallback) {
//WebRtcPeer.prototype.processSdpAnswer = function(sdpAnswer, successCallback) {
var answer = new RTCSessionDescription({
    type : 'answer',
    sdp : sdpAnswer,
});

console.log('Kurento-Utils: SDP answer received, setting remote description');
var self = this;
self.pc.onaddstream = function(event) {
    var objectURL = URL.createObjectURL(event.stream);
    //Added the string below to create the callback
    callbackEvent(event.stream);
};

self.pc.setRemoteDescription(answer, function() {
    if (self.remoteVideo) {
        var stream = self.pc.getRemoteStreams()[0];
        //console.log('Kurento-Utils: Second self.pc');
        //console.log(self.pc)
        self.remoteVideo.src = URL.createObjectURL(stream);
    }
    if (successCallback) {
        successCallback();
    }
}, this.onerror);
因此,在本例中,回调函数是recordVideo,它被传递到“event.stream”

因此,我希望在函数“onPlayOffer”中,我可以将对象localStream(全局声明)作为stream(即本地)的副本。变量“stream”是正确的,而变量“localStream”是未定义的

你能帮我弄明白为什么吗? 我已经读到,问题可能出在控制台上,但我试图注释所有console.log行,但没有成功。你能帮助我吗?谢谢大家


(如果有人知道全局获取event.stream对象的更快方法,我将非常感谢您的帮助!)

您是对的,您的问题是异步的

最简单的纠正方法是,将必须跟随异步调用的任何代码/逻辑作为该异步调用的回调

这可以通过改变

    ...
    webRtcPeer.processSdpAnswer(sdpAnswer, recordVideo);

    console.log('DEBUG: ok, AGAIN, localStream: ');
    console.log(localStream);

    yield player.play();
    ...
进入

    ...
    var callback = function (){
        console.log('DEBUG: ok, AGAIN, localStream: ');
        console.log(localStream);

        yield player.play();
    };
    webRtcPeer.processSdpAnswer(sdpAnswer, recordVideo.bind({callback: callback})); // through bind, we are setting the `this` value of the recordVideo.
并将录制的视频修改为

function recordVideo(stream) {
    ...
    this.callback();    // extra line added.
}

您缺少一个收益率,这使得代码如下:

webRtcPeer.processSdpAnswer(sdpAnswer, recordVideo);
在录制视频之前执行

要解决这个问题,就把它放进去

yield webRtcPeer.processSdpAnswer(sdpAnswer, recordVideo);

更新:这是异步函数的问题:recordVideo函数在打印控制台日志后返回localVideo变量。有人知道如何“等待”函数的完全执行吗?
webRtcPeer.processSdpAnswer(sdpAnswer, recordVideo);
yield webRtcPeer.processSdpAnswer(sdpAnswer, recordVideo);