crycode-de / node-pcf8574

Node.js module for controlling each pin of a PCF8574/PCF8574A I2C port expander IC.
GNU General Public License v2.0
1 stars 2 forks source link

UnhandledPromiseRejectionWarning: An other poll is in progress #51

Closed HarterHorst closed 2 years ago

HarterHorst commented 2 years ago

Hi, i have an issue with the library during the process of setting inputPin for multiple pins. I have tried to set the pins via a for loop but that leads to the error message below. Then i tried to set them separately which brought the same result.

Error message is:

(node:1338) UnhandledPromiseRejectionWarning: An other poll is in progress

Regardless of the error message, the code works. But this does not feel good.

When I only set one pin (e.g. PIN 0) I'm not getting any error message.

Any ideas?

Code

var PCF8574 = require('pcf8574').PCF8574;
var i2cBus = require('i2c-bus').openSync(1);

var pcf = new PCF8574(i2cBus, 0x38, true);

pcf.enableInterrupt(17);

pcf.inputPin(0, false);
pcf.inputPin(1, false);
pcf.inputPin(2, false);

//var promChain = Promise.resolve();

//for(pin=0; pin<8; pin++){
//  promChain = promChain.then(function(){
//    return pcf.inputPin(pin, false);
//  });
//}

pcf.on('input', (data) => {
  console.log('input', data)
});

process.on('SIGINT', function(){
    pcf.removeAllListeners();
    pcf.disableInterrupt();
});
crycode-de commented 2 years ago

Hi, you need to wait until the returned promise from the inputPin method is resolved before you can call inputPin again. So your approach with the promise chain is basically right, but there are two issues:

1) you havn't declared the pin variable. 2) When the callback of .then(...) gets executed, pin will always be 8.

Try running this code snippet:

var promChain = Promise.resolve();
for(pin=0; pin<8; pin++){
  promChain = promChain.then(function(){
    console.log(pin);
    //return pcf.inputPin(pin, false);
  });
}

This will log eight times 8.

To get the correct value for pin you need declare it as a local variable in the for loop using the let keyword like this:

let promChain = Promise.resolve();
for(let pin=0; pin<8; pin++){
  promChain = promChain.then(function () {
    console.log(pin);
    //return pcf.inputPin(pin, false);
  });
}
HarterHorst commented 2 years ago

Yes, that was the problem. Thanks for that. I should check the basics next time. for loops are not so difficult.