递归调用诺言方法将变得无限

时间:2019-01-05 10:43:27

标签: javascript promise

我正在调用方法a,该方法将返回一个Promise,并且在其中调用一个方法,该方法将执行一些操作并更新count变量。我希望所有的诺言都可以在计数结束后完成,但是在达到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));

2 个答案:

答案 0 :(得分: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 :(得分: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))