i am trying to use async await in my code but i am having some issues. I am trying to initiate a transaction anytime there is a free modem port. Currently,these are the number of resources in my database
open ports: 1
queued transactions: 3
let ttyUSB0mtnmodem = serialportgsm.Modem();
ussd(ttyUSB0mtnmodem);
async function searchForFreePorts() {
while (true) {
await db.read();
let freePorts = await db.data.mtnPorts.filter(obj => obj.status == "free");
let queuedTrans = await db.data.mtnQueue.filter(obj => obj.status == "queued");
if (freePorts.length > 0) { //if there are any open ports, proceed
await freePorts.forEach((port, i) => {
if (i < queuedTrans.length) { // if free ports is less than the queued transactions, continue loop
console.log("here");
let transaction = queuedTrans[i];
initiateWithdrawal(port, transaction);
}
})
}
await sleep(1000);
}
}
searchForFreePorts();
function initiateWithdrawal(port, transaction) {
let dev = port.dev + "mtnmodem";
eval(dev).on('open', async () => {
console.log(`\nModem Sucessfully Opened`);
//set port status to busy
//perform transaction
//when done,remove from queued transactions and set port status to free
await eval(dev).close();
})
eval(dev).on('close', data => {
//whole message data
console.log(`Event Close: ` + JSON.stringify(data));
});
eval(dev).open('/dev/' + port.dev, options);
}
the issue here is that, the first initiateWithdrawal() call opens the modem once and performs the first transaction correctly, but whenever it's called again,it opens the modem twice even though only one port is free.
first call logs
using : ttyUSB0 mtn
Modem Sucessfully Opened
second call logs
using : ttyUSB0 mtn
Modem Sucessfully Opened
using : ttyUSB0 mtn
Modem Sucessfully Opened
is there anything i am doing wrong?