RTCPeerConnection.createAnswer callback returns un

2020-02-14 06:11发布

问题:

Following is my code to answer the incoming call:

var pc = connection.pc;
pc.setRemoteDescription(sdp,function() {
 pc.createAnswer(function(answer) {
  pc.setLocalDescription(answer,function() {
   // code for sending the answer
 }) 
 })
})

The above code works fine for chrome, but when i run the same in mozilla, the answer obtained from pc.createAnswer callback is undefined. As a result of which it gives me following error:

TypeError: Argument 1 of RTCPeerConnection.setLocalDescription is not an object.

回答1:

The problem is you're not checking errors, specifically: not passing in the required error callbacks.

setRemoteDescription and setRemoteDescription require either three arguments (legacy callback style) or one (promises), but you're passing in two. Same for createAnswer minus one.

The browser's JS bindings end up picking the wrong overload, returning you a promise which you're not checking either, effectively swallowing errors.

Either add the necessary error callbacks:

var pc = connection.pc;
pc.setRemoteDescription(sdp, function() {
  pc.createAnswer(function(answer) {
    pc.setLocalDescription(answer, function() {
      // code for sending the answer
    }, function(e) {
      console.error(e);
    });
  }, function(e) {
    console.error(e);
  });
}, function(e) {
  console.error(e);
});

Or use the modern promise API:

var pc = connection.pc;
pc.setRemoteDescription(sdp)
  .then(() => pc.createAnswer())
  .then(answer => pc.setLocalDescription(answer))
  .then(() => {
    // code for sending the answer
  })
  .catch(e => console.error(e));

The promise API is available natively in Firefox, or through adapter.js in Chrome. See fiddle.

And always check for errors. ;)