看起来我的使用 await
的方式并不像我理解的那样。
我认为一个 async
函数和 await
关键字可以用于返回 Promise 的调用(例如 navigator.mediaDevices.getUserMedia
),它会暂停函数执行(就像生成器函数一样),直到 Promise 解决,然后继续执行函数。
尽管我正在等待调用,但它立即返回,我的控制台日志的顺序出现了问题。特别是以“reducer”开头的控制台日志先于以“getter”开头的控制台日志出现,而根据堆栈跟踪运行的方式应该相反/与我(认为)的运行方式相反。
有人能告诉我这里发生了什么吗?
异步辅助函数 getter:
const getLocalStream = async () => {
try {
const localStream = await navigator.mediaDevices.getUserMedia({ video: true, audio: true });
console.log('getter localStream', localStream);
console.log('about to return')
return localStream;
}
catch (err) {
console.error(err);
}
}
export default getLocalStream;
Reducer/store:
import getLocalStream from './getLocalStream';
const reducer = (state = {}, action) => {
switch (action.type) {
case 'SEND_CALL': {
const { id } = action;
const localStream = getLocalStream();
console.log('reducer localStream', localStream);
const call = state.peer.call(id, localStream);
return { ...state, call };
}
default:
return state;
}
};
控制台:
reducer localStream Promise {<pending>}
Uncaught TypeError: Failed to execute 'addStream' on 'RTCPeerConnection': parameter 1 is not of type 'MediaStream'
getter localStream MediaStream {id: "B6Foz1jheGvnMqjiqC4PFoOvUVahF04zigzm", active: true, onaddtrack: null, onremovetrack: null, onactive: null, …}
about to return
getLocalStream
的执行。但它不会暂停其调用者(reducer
)的执行 - 它只是向其返回一个 Promise。 - Bergi