This topic is locked

Await in ClientBefore Button javascript code error

7/8/2022 4:46:09 PM
PHPRunner General questions
Davor Geci authorDevClub member

Hello,
what I need to do is to read a serial data string that is coming from a serial port.
To do that I follow the instructions from https://web.dev/serial/#read-port

I've added a custom button in Add page and in ClientBefore code block I added this code:


// Prompt user to select any serial port.
const port = await navigator.serial.requestPort();

// Wait for the serial port to open.
await port.open({ baudRate: 9600 });

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);
}

submit();
return false;

But getting errors in console:
Uncaught SyntaxError: await is only valid in async functions and the top level bodies of modules

What I'm doing wrong?

Thanks,
Davor

Sergey Kornilov admin 7/8/2022

Googling the error message points to this article:
https://stackoverflow.com/questions/49432579/await-is-only-valid-in-async-function

You cannot simply use await in ClientBefore event. According to the aticle there is much more work than that.