我正在尝试为与串行端口接口的Promise添加一个timout。将超时应用于承诺的脚手架基于Italo Nascimento's blog article(请参见代码段中的promiseTimeout
函数)。
由于node-serialport
不提供Promise接口,因此我在stream interface周围写了一个小的包装程序(请参见函数dummyDetectPort
),该包装程序可以正常工作。但是,当将此承诺传递给promiseTimeout
以便使承诺访问串行端口超时时,该承诺既不会得到解决也不会被拒绝。因此,无论给定的超时时间为ms
,“限制”承诺都是超时承诺。
我在哪里不明白这一点?为什么在与timeout
承诺竞争时,序列承诺会按预期工作,但没有得到解决或拒绝?
'use strict';
const SerialPort = require('serialport');
const Readline = require('@serialport/parser-readline');
// https://italonascimento.github.io/applying-a-timeout-to-your-promises/
const promiseTimeout = (ms, promise) => {
// Create a promise that rejects in <ms> milliseconds
let timeout = new Promise((resolve, reject) => {
let id = setTimeout(() => {
clearTimeout(id);
reject(`Timed out in ${ms} ms.`);
}, ms)
})
// Returns a race between our timeout and the passed in promise
return Promise.race([
timeout,
promise,
])
}
const dummyDetectPort = (portName) => {
console.log(`Promise created (${portName}).`);
return new Promise( (reject, resolve) => {
const port = new SerialPort(portName);
const parser = port.pipe(new Readline());
port.write(`${portName}\n`);
parser.on('data', (data) => {
console.log(`Received data on ${portName}: ${data}`);
port.close( (err) => reject(err) );
console.log(data == portName);
if (data == portName)
{
const msg = `Promise resolved (${portName}).`;
return resolve(msg);
}
else
{
const msg = `Promise rejected (${portName}).`;
return reject(msg);
}
})
})
}
const main = (portName) => {
promiseTimeout(60000, dummyDetectPort(portName))
// dummyDetectPort(portName)
.then(result => console.log(result))
.catch(err => console.log(err))
}
main('/dev/tty.usbserial-FTG7L3FX');