我正在使用 node-serialport 与一块硬件进行通信。它只是写一个命令并接收一个响应。
https://serialport.io/docs/en/api-parsers-overview
以下代码有效:
const port = new SerialPort(path);
const parser = port.pipe(new Readline({ delimiter: '\r', encoding: 'ascii' }));
const requestArray = [];
parser.on('data', (data) => {
// get first item in array
const request = requestArray[0];
// remove first item
requestArray.shift();
// resolve promise
request.promise.resolve(data);
});
export const getFirmwareVersion = async () => {
let resolvePromise;
let rejectPromise;
const promise = new Promise((resolve, reject) => {
resolvePromise = resolve;
rejectPromise = reject;
});
const title = 'getFirmwareVersion';
const cmd = 'V\r';
requestArray.push({
title,
cmd,
promise: {
resolve: resolvePromise,
reject: rejectPromise
}
});
await v2Port.write(cmd);
return promise;
};
然后从我的应用程序(用电子/反应编写)我可以调用该函数:
<Button onClick={() => {
let data = await _api.getFirmwareVersion();
console.log('done waiting...');
console.log(data);
}>
Click Me
</Button>
无论如何我可以重构这段代码以使其更简洁吗?
有没有办法从async
函数中获取 Promise,而不必做出新的 Promise?
有没有办法利用已经存在的转换流并以某种方式将 Promise 传递到那里?
我也是 async/await 的新手,想避免使用回调,尤其是在 React/Redux 方面。
I aim to have a lot of these endpoints for the api (i.e. getFirmwareVersion
, getTemperature
, etc...). So I want to make the code as concise as possible. I don't want the UI to have any underlying knowledge of how the API is getting the data. It just needs to request it like any other API and wait for a response.