[英]How do I make an Oauth2 REST request using Node and node-rest-client?
[英]how to use bluebird to promisify node-rest-client
我正在尝试使node-rest-client库合格(尝试过restler,但似乎不能重新进入,并导致与并行POST到同一端点的问题)。
我曾尝试对blueler docs中的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);
成功将承诺的功能添加到restClient
但是,当我调用postAsync(url, options).then(...)
,node-rest-client库引发错误,指出回调未定义。
据我所知,这应该行得通,但似乎promisifier中提供的回调函数并未将其传递到库中。
我希望对Bluebird有更多经验的人可以看到我在做什么错。
的.apply
的方法也只需要两个参数-在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);
});
};
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.