我正在调用一个方法,该方法返回一个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));
解决方法:
// 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"));
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。