Promisifying Callbacks in Node.js [duplicate]

自作多情 提交于 2020-01-06 18:36:11

问题


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!!!


回答1:


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);
});



回答2:


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);});


来源:https://stackoverflow.com/questions/41663281/promisifying-callbacks-in-node-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!