在Node.js中实现回调

在Node.js中实现回调

问题描述:

我有这个节点js应用程序,它使用了几个回调函数,这些函数我想尽量使之无效。

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

任何有见识的帮助!

常见模式是:

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