jdog
jdog

Reputation: 10759

Not sure why promise still being returned when i am await

I am not sure why I am stilling getting an error saying a Promise is returned not a stream. Do I have my async and await correct?

const audioStreamer = useUserMedia({
    constraints,
    streamListener: async (stream) => {
      console.log('Streamlistener in streamcontroller line 64 abut to connect');
      console.log(`stream line 238 is ${stream}`);
      stream = await getMedia(constraints).then(stream);
      console.log(`stream line 240 is ${stream}`);
      let source = audioContext.createMediaStreamSource(stream); <--- stream is Promise here
      source.connect(analyser);
    },
    dataCb: (data) => socket.emit('stream', data),
  });

  async function getMedia(constraints) {
    let stream = null;

    try {
      stream = await navigator.mediaDevices.getUserMedia(constraints);
      /* use the stream */
    } catch (err) {
      /* handle the error */
    }
  }

Upvotes: 1

Views: 25

Answers (1)

Drew Reese
Drew Reese

Reputation: 202618

You should probably return stream after waiting for it. async functions implicitly return a Promise.

async function getMedia(constraints) {
  let stream = null;

  try {
    stream = await navigator.mediaDevices.getUserMedia(constraints);
    /* use the stream */
  } catch (err) {
    /* handle the error */
  }

  return stream; // <-- return value from function
}

And await it in calling function.

streamListener: async (stream) => {
  console.log('Streamlistener in streamcontroller line 64 abut to connect');
  console.log(`stream line 238 is ${stream}`);

  stream = await getMedia(constraints); // <-- wait

  console.log(`stream line 240 is ${stream}`);
  let source = audioContext.createMediaStreamSource(stream);

  source.connect(analyser);
},

Upvotes: 1

Related Questions