从异步等待功能获取Bluebird Promise [英] Get Bluebird Promise from async await functions

查看:95
本文介绍了从异步等待功能获取Bluebird Promise的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找使用Node v7.6或更高版本的方法来获得 Bluebird Promise(或其他任何一种)非本地诺言).当调用异步函数时.

I am looking for a way, with Node v7.6 or above, to get a Bluebird Promise (or any non-native promise) when an async function is called.

我可以采用相同的方式:

In the same way I can do:

global.Promise = require('Bluebird'); // Or Q/When
var getResolvedPromise = () => Promise.resolve('value');

getResolvedPromise
  .tap(...) // Bluebird method
  .then(...);

请参阅:我可以使用global.Promise = require("bluebird")

我希望能够做类似的事情:

I want to be able to do something like:

global.Promise = require('Bluebird'); // Or Q/When
var getResolvedAsyncAwaitPromise = async () => 'value';

getResolvedAsyncAwaitPromise()
  .tap(...) // Error ! Native Promises does not have `.tap(...)`
  .then(...);

我知道我随时可以使用类似的东西:

Bluebird.resolve(getResolvedAsyncAwaitPromise())
  .tap(...);

但是,我想知道 是否可以更改AsyncFunction返回的默认Promise.构造函数似乎是封闭的:

But I was curious if there would be a way to change the default Promise returned by AsyncFunction. The constructor seems enclosed:

请注意,AsyncFunction不是全局对象.可以通过评估以下代码来获取.

Note that AsyncFunction is not a global object. It could be obtained by evaluating the following code.

Object.getPrototypeOf(async function(){}).constructor

AsyncFunction上的MDN参考

如果无法更改AsyncFunction的Promise构造函数,我想知道此锁定的原因.

If there is no way to change the AsyncFunction's Promise constructor, I would like to know the reasons of this locking.

谢谢!

推荐答案

是否可以更改AsyncFunction返回的默认Promise

Is there a way to change the default Promise returned by AsyncFunction

否.

此锁定的原因是什么

What are the reasons of this locking

劫持所有async function的能力可能是一个安全问题.另外,即使没有问题,在全球范围内进行替换仍然没有用.它会影响您的整个领域,包括您正在使用的所有库.他们可能依赖使用本地承诺.尽管可能需要使用两个不同的Promise库,但是您不能使用它们.

The ability to hijack all async functions could be a security issue. Also, even where that is no problem, it's still not useful to do this replacement globally. It would affect your entire realm, including all libraries that you are using. They might rely on using native promises. And you cannot use two different promise libraries, although they might be required.

我希望能够做类似的事情:

I want to be able to do something like:

getResolvedAsyncAwaitPromise().tap(...)

可以要做的是使用

What you can do is to wrap the function at its definition with Promise.method:

const Bluebird = require('Bluebird');
const getResolvedAsyncAwaitPromise = Bluebird.method(async () => 'value');

getResolvedAsyncAwaitPromise()
.tap(…) // Works!
.then(…);

这篇关于从异步等待功能获取Bluebird Promise的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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