简体   繁体   中英

Wait for WebHID response to be ready

I'm sending data to the target device using device.sendReport(reportID, dataBuffer) of WebHID , but trying to read the response before it gets ready (ie) the response takes time to be generated.

For now by setting timeout for 10ms, I'm able to get the response. Would like to know if there are any better solution for this.

You haven't said how the device provides the response but I assume that it is in the form of an input report. In that case the Promise returned by sendReport() isn't particularly interesting but instead you want to listen for an inputreport event that will be fired at the HIDDevice . If you want you can turn this into a Promise like this,

const response = new Promise((resolve) => {
  device.addEventListener('inputreport', resolve, { once: true });
});
await device.sendReport(...your data...);
const { reportId, data } = await response;

Once the response is received it will be stored in data .

Note that this assumes that the device only generates input reports in response to a request. For a device with more complex communications you may want to have an inputreport event listener registered at all times and process input reports based on their report ID or other factors. HID does not support any backpressure so if you don't have an inputreport event listener registered when a report is sent by the device it will be discarded.

For this type of action you should use asynchronous code. When sending/receiving things to or from a server, this action is a 'Promise' which is asynchronous.

It'll look something like this (using the fetch api as an example):

With callbacks (which are optional)

myFunction = () => {
  fetch('POST', data)
    .then((response) => {
      console.log(response);
    })
    .catch((error) => {
      console.warn(error);
    });
}

With async/await. This is not recommended in most cases, as this assumes that the request will succeed.

myFunction = async () => {
  const response = await fetch('POST', data);
  console.log(response);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM