Promisifying Callbacks in Node.js
This question already has an answer here:
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);
});
你需要为此使用蓝鸟。
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);});
链接地址: http://www.djcxy.com/p/55532.html
上一篇: 异步等待回调不是一个函数