-1

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 .

Mohammad
  • 36
  • 1
  • 8

1 Answers1

0

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.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • that's true but i cant understand why it have an ID outside of function – Mohammad May 24 '22 at 09:29
  • I don't understand why you think it does. – Quentin May 24 '22 at 09:30
  • well i can see my server response to myPeer.id when its created outside of `createPeer()` ===> e06880b7-ec1e-4110-8021-5cb91a794584 instead of `null` – Mohammad May 24 '22 at 09:36
  • @Mohammad — The time delay between calling `new Peer()` and the user clicking the button counts as having "waited for it to connect to the brokering server" (although its a shonky approach). – Quentin May 24 '22 at 09:38