使用递归调用promise方法导致无限循环。

3

我正在调用一个返回承诺的方法a,在其中我调用了一个执行某些操作并更新计数变量的方法。我希望所有的承诺在计数完成后都能完成,但是它在达到值10后没有停止。

  var count = 0;

  function a(p){
   return new Promise((resolve, reject) =>{
    console.log(count);
    if(count == 10) {console.log('sdfsdfsd'); resolve(Date.now()); }

    callee().then(() => { count++; a(); } )
  })
 }

 function callee(){ return new Promise((resolve) => resolve())}

 a(1).then((res) => console.log(res)).catch((res) => console.log(res));

避免使用Promise构造反模式callee应该是唯一使用new Promise的函数。 - Bergi
@Bergi 我刚使用Promise复制了实际场景。在实际代码中,我有两个异步的http调用。 - Sachin
是的,那么在 callee 中执行。重点是 a 不应该使用 new Promise - 参见 @adz5A 的可行答案。 - Bergi
2个回答

2
// So you have a function `foo` which returns a promise eventually resolved, you want to write a function
// `bar` that will call this function n times, waitinng between each call for the returned promise to be
// resolved. This function will itself return a promise

// this function returns a promise which is resolved after one second
const foo = () => new Promise(resolve => setTimeout(resolve, 1000));

// Recursively call the foo function until 0 is reached.
// This will actually create a chain of promises which settle after one second.
// It also uses the fact that if you return a promise `a` in the `then` handler the returned
// promise `b` will only settle when `a` is resolved.
const bar = n => {
    if (n === 0) return Promise.resolve();

    return foo().then(() => bar(n-1));
};

bar(10).then(() => console.log("done"));

1

var count = 0;

function a(p) {
    return new Promise((resolve, reject) => {
        console.log(count);
        if (count == 10) { console.log('sdfsdfsd'); return resolve(Date.now()); }

        return callee().then(() => {
            count++;
            return resolve(a());
        })
    })
}

function callee() { return new Promise((resolve) => resolve()) }

a(1).then((res) => console.log("res",res)).catch((res) => console.log(res))


执行此操作时,在调用函数的 then 块中没有安慰值。 - Sachin
我在控制台看到数字,你需要调试哪个代码块? - Vadim Hulevich
函数a()的已解决函数即then块的结果。在最后一行中使用控制台。 - Sachin

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接