[英]Recursive function is only resolving if it runs once
我有一个调用自己的递归函数。 因为它是在承诺中,所以当我再次调用它时,承诺链就连我都无法退回,即使我退还了它。 这是我的职能...
let depth = 0;
const maxDepth = 1;
main();
function main()
{
reccursive.then(
function(response)
{
console.log('all finished!');
});
}
function reccursive()
{
return new Promise((resolve, reject)=>
{
console.log('in recursive function');
if (depth === maxDepth)
{
console.log('hit max depth');
return resolve();
}
console.log('not max depth, increasing');
depth++;
return reccursive();
});
}
如果最大深度为0,它将运行一次,然后解析就好了。
问题是,您需要创建多个Promises吗? 如果不是,则创建一个Promise,并具有一个类似于递归函数的内部函数。
function recursive(depth = 0, maxDepth = 5) { console.log('in recursive function'); function inner(resolve){ if (depth === maxDepth){ console.log('hit max depth'); resolve(depth); return; } console.log('not max depth, increasing'); depth++; inner(resolve); } return new Promise((resolve, reject)=>{ inner(resolve); }); } recursive().then(depth=>console.log(depth))
您缺少首次通话的解决方法。 而不是return reslove()
reccursive().then(function(){ resolve();});
而是使用reccursive().then(function(){ resolve();});
let depth = 0;
const maxDepth = 1;
main();
function main()
{
reccursive.then(
function(response)
{
console.log('all finished!');
});
}
function reccursive()
{
return new Promise((resolve, reject)=>
{
console.log('in recursive function');
if (depth === maxDepth)
{
console.log('hit max depth');
return resolve();
}
console.log('not max depth, increasing');
depth++;
reccursive().then(function(){ resolve();});
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.