问题
Working on the communication between PC and an Arduino-based Hardware with Node.js. This last device is implemented with G-Code, so if i send ‘G0’ I will receive two lines; one to confirm that the instruction has been received and a second one with data.
I would like to use async/await but something is wrong... here goes the code:
'use strict'
const SerialPort = require('serialport')
const Readline = SerialPort.parsers.Readline
const cardPort = new SerialPort('COM6', {
baudRate: 115200,
parity: 'none',
stopBits: 1,
dataBits: 8,
flowControl: false,
usePromises: true,
}, function(err) {
if (err){
console.log('error: ', err.message)
port.close()
} else {
}
})
const cardParser = new Readline({ delimiter: '\r\n' })
cardPort.pipe(cardParser)
function checkCard(port, parser){
port.write('G0\n', function () {
console.log('message written')
parser.on('data', (data) => {
console.log(data)
return (data)
})
})
}
async function run () {
const id = await checkCard(cardPort,cardParser)
console.log(`ID response is: ${id}`)
}
run()
and this is the response I got:
ID response is: undefined
message written
Received: G0
ENCR1PT3R!
why ID response is not waiting until checkCard is executed?
Thanks in advance
回答1:
checkCard
should return Promise
to work, but looks like port.write
is callback based. Enclose it in new Promise
for it work.
function checkCard(port, parser){
return new Promise(function(resolve, reject) {
port.write('G0\n', function () {
console.log('message written')
parser.on('data', (data) => {
console.log(data)
resolve(data)
})
})
});
}
来源:https://stackoverflow.com/questions/50857586/async-await-using-serialport-in-node-js