From declaring variables locally to accessing them globally in JavaScript

I'm facing an issue with JavaScript, webRTC, and Kurento that I can't seem to resolve on my own. My problem arises when trying to store the remote stream from a local variable into a global variable. I'll explain the steps leading to the issue: Firstly, the Kurento webRtcEndpoint function is called like this:

webRtcPeer = kurentoUtils.WebRtcPeer.startRecvOnly(videoElement, onPlayOffer, onError);

It triggers the "onPlayOffer" function which looks like:

function onPlayOffer(sdpOffer) {
co(function * () {
    try {
        if (!client) client = yield kurentoClient(args.ws_uri);

        pipeline = yield client.create('MediaPipeline');
        var webRtc = yield pipeline.create('WebRtcEndpoint');
        var player = yield pipeline.create('PlayerEndpoint', { uri: args.file_uri });

        yield player.connect(webRtc);
        var sdpAnswer = yield webRtc.processOffer(sdpOffer);
        webRtcPeer.processSdpAnswer(sdpAnswer, recordVideo);

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

        yield player.play();

I made changes to the processSdpAnswer function to handle the stream like this:

WebRtcPeer.prototype.processSdpAnswer = function(sdpAnswer, callbackEvent, 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);
    callbackEvent(event.stream);
};

self.pc.setRemoteDescription(answer, function() {
    if (self.remoteVideo) {
        var stream = self.pc.getRemoteStreams()[0];
        self.remoteVideo.src = URL.createObjectURL(stream);
    }
    if (successCallback) {
        successCallback();
    }
}, this.onerror);

In this scenario, the recordVideo function acts as a callback to store the stream globally:

function recordVideo(stream) {
console.log("DEBUG: called function recordVideo()");
localStream = stream;
console.log("DEBUG: Copied stream -> localStream:");
console.log(localStream);
console.log("DEBUG: the stream object contains:");
console.log(stream);}

However, when I check the value of "localStream" in the onPlayOffer function, it appears as UNDEFINED, while "stream" is correct. I'm unsure why this is happening. I've tried removing console.log statements as a possible solution, but it didn't work. Can someone please assist me in figuring out the issue? Any help is greatly appreciated!

(If anyone knows a quicker way to access the event.stream object globally, I would be grateful for any suggestions!)

Answer №1

It appears that your issue is related to asynchronous processing.

A simple solution to correct this issue is by ensuring that any code or logic that needs to execute after the asynchronous call is placed within a callback function for that call.

This can be achieved by making the following changes:

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

        yield player.play();
    };
    webRtcPeer.processSdpAnswer(sdpAnswer, recordVideo.bind({callback: callback})); // By using bind, we set the 'this' value for recordVideo.

Additionally, adjust the recordVideo function to:

function recordVideo(stream) {
    ...
    this.callback();    // New line added for callback execution.
}

Answer №2

Your code is currently missing a crucial yield statement, causing the execution order to be incorrect. The following code snippet demonstrates the issue:

webRtcPeer.processSdpAnswer(sdpAnswer, recordVideo);

This results in running the code before recordVideo is properly executed.

To fix this issue, simply replace the code with:

yield webRtcPeer.processSdpAnswer(sdpAnswer, recordVideo);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

javascript creating unique model instances with mongoose

I've searched through related posts without finding exactly what I need. Currently, I am working on building a backend rest API and conducting tests to collect data. Each test has its own model which is associated with collections in the database. T ...

Top location for Cordova/Phonegap events in AngularJS

Currently, I am working on an AngularJS Cordova app and so far everything is progressing smoothly. My next objective is to integrate Cordova plugins into the application, specifically the Cordova Connect plugin, which will allow me to monitor network conne ...

"Exploring the realms of AngularJS through callback functions and variable scopes

I am currently experiencing an issue with JavaScript in general. Specifically, I am trying to update a list after invoking a callback from two separate files. Here is the description of the callback : this.modify = function(){ var self = this; v ...

What is the best way to trigger the ajax request with the same post parameter upon pressing the browser's back button?

Is there a way to remember the post parameters and resend an AJAX request when the browser back button is pressed? I have searched online and found a couple of methods: Using localsotrage or document.location.hash when the page unloads. Using cookie ...

The tooltips on a resized jQuery Flot chart are displaying in the incorrect location

Currently, I am utilizing the flot library for my chart. I am facing an issue with getting the correct tooltips to display when I scale the chart using this CSS rule: transform: scale(0.7); The flot source relies on the function findNearbyItem to locate ...

Exploring nested JSON objects with Jade and Express

Currently, I'm feeling a bit frustrated as I struggle to find a way to access the "media" content from this specific JSON object using Jade. { "summary":"Jose Mourinho names his Real Madrid side to face Borussia Dortmund in the Champions Lea ...

display rails view using ajax

I have developed a new form that I would like to render using ajax in case it fails validations. In my controller, the code looks like this: def create event = CEvent.new(params[:c_event]) respond_to do |format| if event.save format.html { ...

Adjust transparency according to the information extracted from the AnalyserNode

Currently, I am exploring ways to animate text opacity based on the volume of an audio file. While browsing online, I came across this specific codepen example, which showcases a similar concept. However, as I am relatively new to JavaScript, I find it ch ...

The getElementBy method is failing to pass the value in the document

Here is the javascript code snippet I am using: document.getElementById('district').value = dist.long_name "this line is passing the value" document.getElementById('city').value = route.long_name "this doesn&apos ...

Detect the "@" character through keyUp for the implementation of @mentions feature

I am currently working on implementing an @mention feature using Vue and Vanilla JS, but I am facing issues with targeting the "@" character specifically. Within my template: <trix-editor ref="trix" @keyup="listenForUser" ></trix-editor& ...

Using Javascript to dynamically copy text to the clipboard

Is there a way to create a function that can automatically copy the current URL in the address bar to the clipboard? Before jumping to conclusions, hear me out: I'm looking for a solution where the copying process happens dynamically, not just when ...

How can I streamline a kendo UI MVC project by eliminating unnecessary components?

After switching my MVC 5 project to utilize Kendo UI, I've noticed a significant increase in the number of files being used. Since there is no need for supporting other cultures at the moment, can I confidently delete the files within the messages an ...

What are the steps to fix a timeout error with React.js and socket.io acknowledgements?

My setup includes a Node.js server and a React.js client application. Data is exchanged between them using socket.io, but I'm running into an issue with implementing acknowledgment. Whenever I try to implement acknowledgment, I receive a timeout error ...

Using Three JS: Import an OBJ file, move it to the center of the scene, and rotate around it

I am trying to figure out how to load an OBJ file and translate its coordinates to the world origin (0,0,0) in order to make orbit controls function smoothly without using Pivot points. My goal is to automatically translate random OBJ objects with differe ...

Learn how to apply inline styles to multiple objects within a single element using React

In my project using React, I am attempting to apply styles only to a specific element within another element. Here is an example with an h1 tag: const Header = () => { const firstName = "Ashraf"; const lastName = "Fathi"; const date = new Date() ...

What changes do I need to make in order for this code to be compatible with Google Sites?

I am working on creating a random redirect button and need to modify the code below in two ways: <script> <!-- /* Random redirect button- From JavaScript Kit (http://javascriptkit.com) Hundreds of scripts available for free! Please keep this cred ...

Tips for applying stroke and shadow effects specifically when the mouse is moving over a canvas:

How can we create a shadow and stroke effect for circles drawn using HTML canvas only during mouse hover? I have two circles and would like to add a shadow and stroke effect when the mouse hovers over them. However, the issue is that once the mouse moves ...

The Node function will yield a BluebirdJS Promise

I've encountered a minor issue with this script. While it functions properly, the "runTenant" method is not returning a promise that needs to be resolved with "all()". Here's the code snippet in question: Promise.resolve(runTenant(latest)).then ...

Expanding the width of Material UI Javascript Dialog Box

Currently, I am utilizing the dialog feature from Material UI in my React JS project and I am looking to expand its width. After some research, I discovered that there is a property called maxWidth which allows you to adjust the width of the dialog. Howe ...

How can we integrate fixed-data-table-2 sorting with an existing redux store?

Any help or advice you can offer would be greatly appreciated. I am still fairly new to using react. I recently took on a project for a client that was already in progress, and everything has been going smoothly up until now. I've come across a stumb ...