在Node.js中实现回调 [英] Promisifying Callbacks in 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);
});
这篇关于在Node.js中实现回调的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文