javascriptwebrtcpeerjspeer

why in javascript i cant create object in this function?


i have a problem with creating object inside my function i know its a void function but i don't need to return any data

let btnConnect = document.getElementById('connect')
let btnConnectedDrive = document.getElementById('ConnectedDrive')

function createPeer() {
    let myPeer = new Peer()
    console.log(myPeer.id)
    let socket = new WebSocket('ws://' + window.location.host + '/ws/myapp/room/' + game_id + '/');
    socket.onopen = () => socket.send(JSON.stringify(
        {
            'username': user,
            'PeerId': myPeer.id
        }
    ),)

}

btnConnect.onclick = () => createPeer();

now when i log myPeer.id its null and same on the server what do you think solution is ? hope you have a very nice time .


Solution

  • See the documentation:

    Other peers can connect to this peer using the provided ID. If no ID is given, one will be generated by the brokering server.

    And the example:

     peer.on('open', function(id) {
       console.log('My peer ID is: ' + id);
     });
    

    It doesn't have an ID because you haven't waited for it to connect to the brokering server and be issued with one.