gpt4 book ai didi

node.js - 从异步等待函数中获取 Bluebird Promise

转载 作者:IT老高 更新时间:2023-10-28 23:16:00 24 4
gpt4 key购买 nike

我正在寻找一种方法,使用 Node v7.6 或更高版本,以获得 Bluebird调用异步函数时的 promise (或任何非本地 promise )。

我可以这样做:

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

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

参见:May I use global.Promise=require("bluebird")

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

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。构造函数似乎是封闭的:

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

如果没有办法改变AsyncFunction的Promise构造函数,我想知道这个锁的原因。

谢谢!

最佳答案

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

没有。

What are the reasons of this locking

劫持所有异步函数的能力可能是一个安全问题。此外,即使这没有问题,在全局范围内进行这种替换仍然没有用。它会影响您的整个领域,包括您正在使用的所有库。他们可能依赖于使用原生 promise 。而且您不能使用两个不同的 Promise 库,尽管它们可能是必需的。

I want to be able to do something like:

getResolvedAsyncAwaitPromise().tap(...)

可以做的就是用Promise.method将函数包装在它的定义中。 :

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

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

关于node.js - 从异步等待函数中获取 Bluebird Promise,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44158629/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com