gpt4 book ai didi

javascript - 为什么我的带有 promise 的递归函数只等待一次?

转载 作者:行者123 更新时间:2023-11-29 20:46:48 24 4
gpt4 key购买 nike

我试图想象“汉诺塔”问题,并尝试使用 promise 让函数等待一个圆盘的运动被动画化(我用 setTimeout 模拟),然后再继续解决问题。此测试代码计算出正确的 Action ,但只等待动画一次,然后立即吐出其余部分:

    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;
}

最佳答案

问题是您立即调用所有调用,然后将它们的返回值作为参数传递给 .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')

关于javascript - 为什么我的带有 promise 的递归函数只等待一次?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54134052/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com