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.authenticate 的 promisified 版本,Bluebird 使它变得非常简单。

module.exports = {
  // Authenticate user against AD
  authenticate: Promise.promisify(ad.authenticate)
};