Get Bluebird Promise from async await functions

狂风中的少年 提交于 2019-12-28 06:01:14

问题


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(...);

See: May I use 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(...);

I know I can use at any moment something like:

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

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

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

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

MDN reference on AsyncFunction

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

Thank you !


回答1:


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

No.

What are the reasons of this locking

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(…);


来源:https://stackoverflow.com/questions/44158629/get-bluebird-promise-from-async-await-functions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!