【问题标题】:how to use bluebird to promisify node-rest-client如何使用蓝鸟来承诺 node-rest-client
【发布时间】:2015-07-18 17:02:39
【问题描述】:

我正在尝试承诺 node-rest-client 库(尝试过 restler,但似乎不能重入,并导致并行 POST 到同一端点的问题)。

我尝试使用与 bluebird docs for restler 中提供的过滤器/promisifer 类似的方法,但似乎无法正常工作。

node-rest-client 使用回调函数和两个参数的组合来成功响应,同时还为超时和错误提供事件发射器。

var Promise = require("bluebird");
var methodNamesToPromisify = "get post put del patch".split(" ");

function EventEmitterPromisifier(originalMethod) {
    // return a function
    return function promisified() {
        var args = [].slice.call(arguments);
        var self = this;
        return new Promise(function(resolve, reject) {
            var emitter = originalMethod.apply(self, args, function(data, response){
              resolve([data, response]);
            });

            emitter
                .on("error", function(err) {
                    reject(err);
                })
                .on("requestTimeout", function() {
                    reject(new Promise.TimeoutError());
                })
                .on("responseTimeout", function() {
                    reject(new Promise.TimeoutError());
                });
        });
    };
};

exports.promisifyClient = function(restClient){

  Promise.promisifyAll(restClient, {
      filter: function(name) {
          return methodNamesToPromisify.indexOf(name) > -1;
      },
      promisifier: EventEmitterPromisifier
  });
}

以及代码中的其他地方:

var Client = require('node-rest-client').Client;

var constants = require('../../config/local.env');

var restClient = new Client();
promisifyClient(restClient);

成功将promisified函数添加到restClient

但是,当我调用 postAsync(url, options).then(...) 时,node-rest-client 库会抛出一个错误,指出回调未定义。

据我所知,这应该可以工作,但似乎 promisifier 中提供的回调函数没有通过库。

我希望在 Bluebird 方面有更多经验的人能够看到我做错了什么。

【问题讨论】:

    标签: javascript node.js bluebird


    【解决方案1】:

    .apply method 只接受两个参数——this 上下文和一个参数数组——但你传递了三个。

    您需要将回调放在数组上,以将其作为最后一个参数传递给originalmethod

    function EventEmitterPromisifier(originalMethod) {
        return function promisified() {
            var args = [].slice.call(arguments),
                self = this;
            return new Promise(function(resolve, reject) {
                function timeout() {
                    reject(new Promise.TimeoutError());
                }
                args.push(function(data, response){
                    resolve([data, response]);
                });
                originalMethod.apply(self, args)
    //                                     ^^^^
                .on("error", reject)
                .on("requestTimeout", timeout)
                .on("responseTimeout", timeout);
            });
        };
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-09-06
      • 1970-01-01
      • 2018-10-23
      • 2017-06-18
      • 2015-04-13
      • 1970-01-01
      • 2014-02-13
      相关资源
      最近更新 更多