简体   繁体   English

Node.js:使用Bluebird将模块函数从回调转换为Promise

[英]Node.js: Converting module functions from callbacks to promises with Bluebird

I have a simple module with a couple of functions to interact with an Active Directory. 我有一个简单的模块,其中包含几个与Active Directory进行交互的功能。

Using the standard callback style, the code works just fine: 使用标准的回调样式,代码可以正常工作:

/**
* 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}`);
}); 

Execution result: 执行结果:

> node client.js
Success: true

The next step was to refactor my lib method to use Promises instead of callbacks: 下一步是重构我的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}`);
});

Execution result: 执行结果:

> node client.js
Success: undefined

So it looks like the status is not being resolved. 因此,看起来status尚未解决。

If I change the AD server URL to something else (to force a connection error and see the rejection) I can see both the resolve and the rejection log: 如果我将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)

What am I doing wrong? 我究竟做错了什么? Can't figure it out. 无法解决。

You are expecting too much of Promise.method() , from which a thrown error or returned value will indeed be promise wrapped, but that's not what you are doing - you are throwing/returning from ad.authenticate's callback. 您对Promise.method()Promise.method()过高,确实会从中包装抛出的错误或返回值,但这并不是您正在做的事情-您正在从ad.authenticate的回调中抛出/返回。

What you want is a promisified version of ad.authenticate , which Bluebird makes extremely simple. 你想要的是一个promisified版本ad.authenticate ,这使得青鸟非常简单。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM