我有一个递归函数,并且只想在递归函数完成时才执行另一个函数。我的代码是:
ngOnInit() {
this.func1(this.myArray.length).then(()=>{
this.func2()
}).catch()
}
func1(len: number) {
return new Promise ((resolve, reject) => {
setTimeout(() => {
console.log('in function func 1 --- ',this.myArray.length);
if (len > 0) {
this.myArray.pop();
this.func1(this.myArray.length).then().catch();
}
}, 1000);
resolve('func1 completed');
});
}
func2(){
console.log('in function func 2')
}
控制台输出:
in function func 2
in function func 1 --- 2
in function func 1 --- 1
in function func 1 --- 0
应该像下面这样:
in function func 1 --- 2
in function func 1 --- 1
in function func 1 --- 0
in function func 2
这里出了什么问题?
您的代码存在违背承诺的问题。 首先,
resolve('func1 completed')
运行时忽略超时。
其次,func1
函数不连接到内部(递归)调用。
您可以通过向调用者返回(解决)内部调用来解决问题:
ngOnInit() {
this.func1(this.myArray.length)
.then(() => this.func2())
.catch((e) => console.error('error', e));
}
func1(len: number) {
return new Promise((resolve) => {
console.log('in function func 1 --- ', this.myArray.length);
setTimeout(() => {
if (len > 0) {
this.myArray.pop();
// resolve(sth) works like return sth
// return the inner promise to build a chain of promises
resolve(this.func1(this.myArray.length));
} else {
resolve('func1 completed');
}
}, 1000);
});
}
func2() {
console.log('in function func 2');
}
但是,
func1
的更好实现可能是:
async func1(len: number) {
console.log('in function func 1 --- ', this.myArray.length);
// wait here
await new Promise((resolve) => setTimeout(resolve, 1000));
if (len > 0) {
this.myArray.pop();
await this.func1(this.myArray.length);
}
return 'func1 completed';
}