问题描述
我最近开始使用异步功能和web.dev串行api。我试图获取串行数据,并使用官方页面上的代码来获取它,但是当我想使其仅在funcctuin调用中读取时,我将无法执行。我想做的是仅在我请求时才将串行数据发送到浏览器,而不是每次串行发送内容时都要发送。
const textDecoder = new TextDecoderStream();
const readableStreamClosed = port.readable.pipeto(textDecoder.writable);
const reader = textDecoder.readable.getReader();
// Listen to data coming from the serial device.
while (true) {
const { value,done } = await reader.read();
if (done) {
// Allow the serial port to be closed later.
reader.releaseLock();
break;
}
// value is a string.
console.log(value);
return value;
}
稍微研究一下之后,我将其放入函数中
async function getSerial(){/* code */}
并在开始时调用它以进行第一次读取
async function serialInit(){
if(soportaSerial){
const ports = await navigator.serial.getPorts(); // Get allowed ports
if(ports == ""){ // if not allowed ports
$("#rectangle").attr("onclick","requestPerm()").css("cursor","pointer");
showNotification("Serial is soported,select board.","#ff403B",-1,"white","1.5vh"); // request select port
}else{ // if allowed port
port = ports[0];
await port.open({ baudrate: 9600 });// Open port
showNotification("Serial connected","#1FDA9A");
allowedSerial = true;
}
data = await getSerial();
console.log(data);
}else {
showNotification("Serial not soported","#ff403B");
}
}
完成此操作后,控制台输出为:
Cycle: 1
Cycle: 2
etc...
就像我已经编程到Arduino板上的东西一样,每1秒打印一次“ Cycle:+ String(cycle)”,但是问题是当我调用该函数时,并没有在控制台上添加日志,而是在打印时接收到新值。 我只想在请求读取和将函数保存到变量输出中时才获取实际周期。 我修改了代码以尝试删除异步,但完成异步后,它不返回任何值,什么也不做。
function getSerial(){
while (port.readable) {
const reader = port.readable.getReader();
try {
const { value,done } = reader.read();
if (done) {
// Allow the serial port to be closed later.
reader.releaseLock();
break;
}
if (value) {
console.log(value);
return value;
}
} catch (error) {
// Todo: Handle non-fatal read error.
}
}
}
我尝试了很多事情。有时说pipeto错误,而其他时候只是破坏代码。 任何建议或帮助我都会非常感激。
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)