0

I have this node js app working with several callback functions which I am trying to promisify to no avail.

Its getting to the point where I dont know if it is even possible. If you can help me promisify the code below I'll probably be able to do the rest of it:

var i2c_htu21d = require('htu21d-i2c');
var htu21df = new i2c_htu21d();


htu21df.readTemperature(function (temp) {
        console.log('Temperature, C:', temp);
});

Any insight helps!!!

George Faraj
  • 43
  • 1
  • 6

2 Answers2

4

The common pattern is:

<promisified> = function() {
    return new Promise(function(resolve, reject) {
       <callbackFunction>(function (err, result) {
           if (err)
               reject(err);
           else
               resolve(result);
       });
    });
}

For your specific example (to which you might want to add error handling):

readTemperature = function() {
    return new Promise(function(resolve) {
       htu21df.readTemperature(function (temp) {
          resolve(temp);
       });
    });
}

readTemperature().then(function(temp) {
    console.log('Temperature, C:', temp);
});
georg
  • 211,518
  • 52
  • 313
  • 390
1

You need to use bluebird for this.

var bluebird = require('bluebird');
var i2c_htu21d = require('htu21d-i2c');
var htu21df = new i2c_htu21d();
var readTemperature = bluebird.promisify(htu21df.readTemperature);


readTemperature().then((temp) => {console.log('Temperature, C:', temp);});
Ebrahim Pasbani
  • 9,168
  • 2
  • 23
  • 30