【问题标题】:Recursive function is only resolving if it runs once递归函数仅在运行一次时才解析
【发布时间】:2019-03-19 23:38:08
【问题描述】:

我有一个调用自身的递归函数。因为它在一个承诺中,当我再次调用它时,承诺链,即使我返回它,我似乎也无法脱身。这是我的功能...

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,它会运行一次然后解析就好了。

【问题讨论】:

  • 你永远不会在递归函数中解析 Promise。你只需要打电话给resolve(),而不是return resolve()
  • 我在做 return resolve();这将解决承诺不会吗?当我再次调用它时,我会返回它返回的任何值,在这种情况下是解析。
  • 好的,我试试,一秒钟
  • 您只解决“最深”的承诺。每次您拨打new Promise 时,也应该有1 次拨打resolve()。这是一种非常糟糕的实现方式。不要使用new Promise()
  • 我拿走了退货但没用。如果我不做新的承诺,我还能怎么做?

标签: javascript recursion promise


【解决方案1】:

问题是,你需要创建多个 Promise 吗?如果不是,则创建一个 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))

【讨论】:

    【解决方案2】:

    您缺少第一次通话的解决方案。而不是return reslove() 使用 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();});
    });
    }
    

    【讨论】:

    • 谢谢,这行得通。我改变了它并做了 recursive().then(resolve);反而。谢谢,我可以在 5 分钟内接受这个
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多