为什么我的带有Promise的递归函数只能等待一次?

时间:2019-01-10 17:33:10

标签: javascript promise towers-of-hanoi

我试图可视化“河内之塔”问题,并尝试使用Promise使函数等待一个光盘的运动动画化(我用setTimeout模拟),然后继续解决问题。此测试代码可以计算出正确的运动,但是只等待动画一次,然后立即吐出其余的动画:

    var A = "rod A";
    var B = "rod B";
    var C = "rod C";

    solve(3,A,C,B);

    function solve (n,source,target,spare) {
        var promise = new Promise(function(resolve,reject){
            if (n==1) {
                setTimeout(function(){
                    console.log("move a disc from "+source+" to "+target);
                    resolve();
                },1000);
            }
            else {
                        solve(n-1,source,spare,target)
                .then(  solve( 1 ,source,target      )  )
                .then(  solve(n-1,spare,target,source)  )
                .then(  resolve()                       );
            }
        });
        return promise;
    }

对于不知道该问题的人,我将代码简化了一点,本质上,目标是打印“移动”七次,并且每次之间的延迟为一秒:

    solveTest(3);

    function solveTest (n) {
        var promise = new Promise(function(resolve,reject){
            if (n==1) {
                setTimeout(function(){
                    console.log("move");
                    resolve();
                },1000);
            }
            else {
                        solveTest(n-1)
                .then(  solveTest( 1 )  )
                .then(  solveTest(n-1)  )
                .then(  resolve()       );
            }
        });
        return promise;
    }

1 个答案:

答案 0 :(得分:2)

问题是您立即调用了所有调用,然后将它们的返回值作为参数传递给.then()。您需要做的是将函数传递给.then()而不是调用它们:

function sleep (ms) {
  return new Promise(function (resolve) {
    setTimeout(resolve, ms)
  })
}

function solve (n, source, target, spare) {
  if (n === 1) {
    return sleep(1000).then(function () {
      console.log('move a disc from ' + source + ' to ' + target)
    })
  } else {
    return solve(n - 1, source, spare, target).then(function () {
      return solve(1, source, target, spare)
    }).then(function () {
      return solve(n - 1, spare, target, source)
    })
  }
}

solve(3, 'rod A', 'rod B', 'rod C')

但是您可以使用asyncawait使阅读更加轻松:

const sleep = ms => new Promise(resolve => { setTimeout(resolve, ms) })

async function solve (n, source, target, spare) {
  if (n === 1) {
    await sleep(1000)
    console.log(`move a disc from ${source} to ${target}`)
  } else {
    await solve(n - 1, source, spare, target)
    await solve(1, source, target, spare)
    await solve(n - 1, spare, target, source)
  }
}

solve(3, 'rod A', 'rod B', 'rod C')