Reputation: 51
I'm trying to search for an active comport open it and then call the then. Everything works exept the then and i don't understand why.
Does anyone have experience with this problem i also tried a simple promise. in that example the then works like supposed to.
let getActiveComPort = new Promise((resolve, reject) => {
let max = 5;
for (let index = 1; index <= max; index++) {
// create a port with the index to test
const port = new SerialPort(`COM${index}`, {
baudRate: 115200,
autoOpen: false,
});
// Try opening the port if error reject
port.open((error) => {
if (error) {
console.log(error, "couldnt open port", index);
return reject(error);
}
});
// if the port is opened resolve promise
port.on("open", () => {
console.log("resolved port", index);
return resolve(port);
});
}
});
getActiveComPort
.then((port) => {
// set ledstrip to white
console.log(
"comport _______________"
);
console.log("comport", port);
port.write(`X002B[290005]\r\n`);
})
.catch((error) => {
console.log(error);
});
`
Upvotes: 1
Views: 635
Reputation: 168966
You'll want to split things so you have a single function that tries a single COM port, then another that tries them in sequence, something like
function tryComPort(index) {
return new Promise((resolve, reject) => {
const port = new SerialPort(`COM${index}`, {
baudRate: 115200,
autoOpen: false,
});
// Try opening the port if error reject
port.open((error) => {
if (error) {
return reject({ index, port, error });
}
});
port.on("open", () => {
return resolve({ index, port });
});
});
}
async function tryComPorts(max = 5) {
for (let index = 1; index <= max; index++) {
try {
return await tryComPort(index);
} catch (err) {
console.error(err);
}
}
throw new Error("Failed all attempts at COM port opening");
}
tryComPorts()
.then(({ index, port }) => {
console.log(`comport ${index}`);
console.log("comport", port);
port.write(`X002B[290005]\r\n`);
})
.catch((error) => {
console.error(error);
});
Upvotes: 1