从异步等待函数中获取 Bluebird Promise [英] Get Bluebird Promise from async await functions

查看:20
本文介绍了从异步等待函数中获取 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.

我可以用同样的方式:

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

没有

这种锁定的原因是什么

劫持所有异步函数的能力可能是一个安全问题.此外,即使在没有问题的情况下,在全局范围内进行此替换仍然没有用.它会影响您的整个领域,包括您正在使用的所有库.他们可能依赖于使用本机承诺.并且您不能使用两个不同的 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(...)

可以做的是在函数定义中使用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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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