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

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

问题描述

Bluebird promisifaction 是一个小魔法,而 request 则相当混乱(它是一个具有方法的对象的函数).

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

具体场景非常简单:我有一个通过 cookie jar 启用 cookie 的请求实例(不使用 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(url) -> Promise
  • 调用 request.getAsync(url) -> Promise
  • 调用 request.postAsync(url, {}) -> Promise
  • 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);

请注意,这意味着 request 不是自由函数,因为 promisification 与原型方法一起使用,因为 this 事先不知道.它仅适用于较新版本的 bluebird.当你需要为 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})

这是因为请求的回调是(err, response, body):Bluebird v3的默认行为是只取第一个成功值参数(即response) 并忽略其他(即 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天全站免登陆