问题描述
我正在寻找使用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:
Object.getPrototypeOf(async function(){}).constructor
如果无法更改AsyncFunction
的Promise构造函数,我想知道此锁定的原因.
If there is no way to change the AsyncFunction
's Promise constructor, I would like to know the reasons of this locking.
谢谢!
推荐答案
否.
劫持所有async function
的能力可能是一个安全问题.另外,即使没有问题,在全球范围内进行替换仍然没有用.它会影响您的整个领域,包括您正在使用的所有库.他们可能依赖使用本地承诺.尽管可能需要使用两个不同的Promise库,但是您不能使用它们.
The ability to hijack all async function
s 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.
getResolvedAsyncAwaitPromise().tap(...)
您可以要做的是使用 Promise.method
:
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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!