你如何正确地宣传请求? [英] How do you properly promisify request?

查看:94
本文介绍了你如何正确地宣传请求?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Bluebird promisifaction有点神奇,请求非常混乱(这是一个与方法一起作为对象的函数)。

Bluebird promisifaction is a little magic, and request is quite a mess (it's a function which behaves as an object with methods).

具体方案很简单:我有一个启用了cookie的请求实例,通过一个cookie jar(不使用 request 的全局cookie处理程序) 。我怎样才能有效地宣传它,以及它支持的所有方法?

The specific scenario is quite simple: I have a request instance with cookies enabled, via a cookie jar (not using request's global cookie handler). How can I effectively promisify it, and all of the methods it supports?

理想情况下,我希望能够:

Ideally, I'd like to be able to:


  • 致电请求(网址) - >承诺

  • 致电 request.getAsync(url) - > Promise

  • call request.postAsync(url,{}) - >承诺

  • call request(url) -> Promise
  • call request.getAsync(url) -> Promise
  • call request.postAsync(url, {}) -> Promise

似乎 Promise.promisifyAll(request)无效(因为我得到postAsync未定义)。

It seems as though Promise.promisifyAll(request) is ineffective (as I'm getting "postAsync is not defined").

推荐答案

以下应该有效:

var request = Promise.promisify(require("request"));
Promise.promisifyAll(request);

请注意,这意味着请求不是一个自由函数,因为promisification适用于原型方法,因为这个是事先不知道的。它只适用于较新版本的蓝鸟。当您需要分支cookie的请求对象时,请重复此操作。

Note that this means that request is not a free function since promisification works with prototype methods since the this isn't known in advance. It will only work in newer versions of bluebird. Repeat it when you need to when forking the request object for cookies.

如果您使用的是Bluebird v3,那么'我想使用 multiArgs 选项:

If you're using Bluebird v3, you'll want to use the multiArgs option:

var request = Promise.promisify(require("request"), {multiArgs: true});
Promise.promisifyAll(request, {multiArgs: true})

这是因为回调对于请求是(错误,响应,正文):Bluebird v3的默认行为是仅取第一个成功值参数(即响应)并忽略其他人(即 body )。

This is because the callback for request is (err, response, body): the default behavior of Bluebird v3 is to only take the first success value argument (i.e. response) and to ignore the others (i.e. body).

这篇关于你如何正确地宣传请求?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆