ES6 中将 async 函数别名为 wait
假设我将函数 fA
实现为同步 调用,而在另一个模块中,此类功能是使用不同的名称(例如 fB
)实现的,并且作为异步调用。
为了使用新模块,如果可能的话,我不想更改函数 fA
的每个现有调用。那么,
有什么办法可以给这样的异步函数调用 fB
一个别名为 fA
吗?例如:
const fA = wait fB
Suppose that I implemented function fA
as a synchronous call, while in another module, such functionality is implemented using a different name (say fB
) and as an asynchronous call.
To use the new module, I don't want to change every single existing calling of my function fA
if possible. So,
Is there any way for me to give such asynchronous function call fB
an alias as fA
? Something like, e.g.:
const fA = await fB
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
不,你不能那样做。
await
仅适用于函数返回的承诺,而不适用于函数本身。而且,没有办法将异步接口转换为同步接口 - 这在 Javascript 中是无法完成的。因此,如果所有使用同步
fA()
的代码现在想要使用返回 Promise 的异步fB()
,那么您将必须在所有地方进行更改现在调用fA()
以使用fB()
通过await
或.then()
返回 wither 的承诺>。没有办法解决这个问题。当然,如果您向我们展示了
fA()
和fB()
的实际代码以及使用fA()
的代码,我们可能对如何最好地调整调用fA()
的现有代码有更具体的想法。现在你的问题是一个理论问题,所以我们只能提供一个理论答案。 Stackoverflow 的答案通常对实际代码更有帮助,因此我们可以提供适合您实际代码的具体建议。
请注意,您可能会尝试为
fB()
制作一个包装器,如下所示:但是,您不能这样做,因为为了使用
await
,您必须使其异步:这实际上与以下内容相同:
这意味着
fA()
包装器仍然只返回一个 Promise,就像fB() 做了(所有
async
函数返回一个承诺),因此这个包装器不会为你的调用者完成任何事情。要使用异步函数,调用者必须使用该函数使用的任何异步调用机制(回调、promise、事件等)。因此,从直接返回值的同步函数切换到通过 Promise 传回结果的异步函数需要更改调用代码。没有办法解决这个问题。
No, you cannot do it that way.
await
only works on a promise that your function returns, not on a function by itself.And, there's no way to turn an asynchronous interface into a synchronous one - it just can't be done in Javascript. So, if all your code that was using synchronous
fA()
wants to now use asynchronousfB()
that returns a promise, you're going to have to change everywhere you are now callingfA()
to use the promise thatfB()
returns wither withawait
or.then()
. No way around that.Of course, if you showed us the actual code for
fA()
and forfB()
and the code that's usingfA()
, we might have more specific ideas on how best to adapt the existing code that callsfA()
.Right now your question is a theoretical question so all we can offer is a theoretical answer. Stackoverflow answers can often be more helpful with real code so we can offer specific suggestions that fit into your actual code.
Note, you might be tempted to try to make a wrapper for
fB()
like this:But, you can't do that because in order to use
await
, you have to make itasync
:Which is really just the same as:
Which means that the
fA()
wrapper still just returns a promise just likefB()
did (allasync
functions return a promise), thus this wrapper doesn't accomplish anything for your caller.To use an asynchronous function, the caller has to use whatever asynchronous calling mechanism the function uses (callback, promise, event, etc...). So switching from a synchronous function that directly returns a value to an asynchronous function that communicates the result back via a promise requires changing the calling code. There is no way around that.