gpt4 book ai didi

javascript - 递归调用 promise 方法是无限的

转载 作者:行者123 更新时间:2023-11-29 10:27:54 27 4
gpt4 key购买 nike

我正在调用一个返回 promise 的方法 a ,在其中我正在调用一个方法来执行一些操作并更新计数变量。我希望所有的 promise 在计数完成后完成,但在达到值 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));

最佳答案

// 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"));

关于javascript - 递归调用 promise 方法是无限的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54051174/

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