Node.js:使用Bluebird将模块函数从回调转换为承诺
Node.js: Converting module functions from callbacks to promises with Bluebird
我有一个简单的模块,其中包含几个与Active Directory交互的函数。
使用标准回调样式,代码工作得很好:
/**
* mylib.js
**/
const ActiveDirectory = require('activedirectory');
// Instantiate AD client
const ad = new ActiveDirectory({
url: 'ldaps://...',
baseDN: 'DC=...',
});
module.exports = {
// Authenticate user against the AD
authenticate: (username, password, callback) => {
// Authentication request
ad.authenticate(username, password, (err, status) => {
callback(err, status);
});
},
};
/**
* client.js
**/
const mylib = require('./mylib');
mylib.authenticate('<username>', '<password>', (err, status) => {
if (err) {
console.log(`Error: ${err}`);
return;
}
console.log(`Success: ${status}`);
});
执行结果:> node client.js
Success: true
下一步是重构我的lib方法,用Promises代替回调:
/**
* mylib.js
**/
const ActiveDirectory = require('activedirectory');
const Promise = require('bluebird');
//...
module.exports = {
// Authenticate user against AD
authenticate: Promise.method((username, password) => {
ad.authenticate(username, password, (err, status) => {
if (err) throw err;
return status;
});
}),
};
/**
* client.js
**/
const mylib = require('./mylib');
myLib.authenticate('<username>', '<password>').then((status) => {
console.log(`Success: ${status}`);
}).catch((err) => {
console.log(`Error: ${err}`);
});
执行结果:> node client.js
Success: undefined
所以看起来status
没有被解析。
如果我将AD服务器URL更改为其他内容(强制连接错误并查看拒绝),我可以看到解析和拒绝日志:
> node client.js
Success: undefined
/Users/.../mylib.js:84
if (err) throw err;
^
Error: connect ECONNREFUSED <IP>
at Object.exports._errnoException (util.js:1036:11)
at exports._exceptionWithHostPort (util.js:1059:20)
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1080:14)
我做错了什么?看不懂
您对Promise.method()
的期望过高,从中抛出的错误或返回的值确实会被承诺包装,但这不是您正在做的-您正在抛出/从ad返回。验证回调。
你想要的是ad.authenticate
的承诺版本,Bluebird使其非常简单。
module.exports = {
// Authenticate user against AD
authenticate: Promise.promisify(ad.authenticate)
};
相关文章:
- 将json回调数据转换为日期
- Facebook转换事件回调
- 使用回调hell将构建转换为promise hell
- 如何将此异步回调转换为生成器
- 在nodejs中将回调转换为promise
- 如何重构“;回调金字塔”;转换为基于承诺的版本
- 触发CSS转换,使用来自Javascript的样式,从内部指令完成回调
- Ember.js从回调转换后
- 无法将 NeDB 节点回调转换为 Bacon EventStream
- 在转换结束时调用回调
- Raphaël转换相对于画布的拖动回调坐标
- 如何将具有两个回调的函数调用转换为promise
- 如何通过'这'转换为setTimeout回调
- 如何将回调示例转换为延迟对象
- Node.js:使用Bluebird将模块函数从回调转换为承诺
- 将嵌套回调转换为承诺
- 在.each()回调(D3)中触发平滑转换
- 扩展ES6承诺,将回调转换为Deferred模式
- 将可以多次调用的Javascript回调转换为promise
- 如何将简单的$http与回调转换为使用承诺