返回承诺的功能在解决方面称呼自己
我是JavaScript和node.js的初学者,所以请原谅我是否可以认为这个问题太简单。
我想知道,如果我有一个返回承诺的函数,并且在Resolve()中再次调用相同的函数,以某种递归中的函数,这是否会导致堆栈溢出,以防其无法解决?
您可以想象它如下:
var someVariable = await myFunction(someInput)
async function myFunction(myInputValue) {
return new Promise(function(resolve, reject) {
// do some computation
if (someCondition) {
resolve(true)
return
} else {
resolve(myFunction(myInputValue))
return
}
})
}
我一直在问这个问题,因为我注意到返回指令已被执行,这(我认为)应该处理该函数的上下文堆栈,并避免遇到诸如堆栈溢出之类的问题。我是否缺少某些东西,然后我冒着问题的危险,还是我是对的,这可以被认为是很安全的做法?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
myFunction
是async
函数,因此您可以将其视为始终返回承诺的函数,并且您可以递归地称其为。解决
在承诺构造函数:而且,也可以安全地从
async
函数:... where 被描述为返回:
但是:应该没有理由返回
中的新承诺
您的使用async
在这里:async
函数已经包装了可以返回的任何东西,因此您可以跳过 expectlicit 。 (仅当您将回调风格的调用调整为Promises时,才保留您对承诺构造函数的使用,这可以在async
和non-async
function中发生。)仍然需要根据
somecontition
以及您对myInputValue
的任何递归修改确定的递归情况是安全的:如果您不保释递归案例,则可能会遇到堆栈溢出,或者您可能 用完了堆的记忆或永远旋转。 (在中async
functions,,但总是将承诺的处理程序带有原本空的堆栈per Promises/A+ 2.2.4和ES6 。myFunction
is anasync
function, so you can treat it as a function that always returns a Promise, and you can call it recursively.It is safe to
resolve
to a Promise in a Promise constructor:And it is also safe to return a Promise from an
async
function:...where
Promise.resolve
is described as returning:However: There should be no reason to return a
new Promise
in your use ofasync
here: Theasync
function already wraps anything it can return in a Promise, so you can skip the explicit Promise construction antipattern. (Reserve your use of the Promise constructor only when you are adapting a callback-style call into promises, which can happen inasync
and non-async
functions.)You'll still need to check that this recursive case is safe based on
someCondition
and whatever recursive modifications you do tomyInputValue
: If you don't bail out of your recursive case, then you might encounter a stack overflow, or you might run out of heap memory or spin forever. (Inasync
functions, the function runs synchronously up until the firstawait
, but Promise handlers are always called with an otherwise-empty stack per Promises/A+ 2.2.4 and ES6.)