typescriptasync-await

typescript settimeout in nested recursive function


I am trying to put settimeout in recursive function call where main function called recursively and subfunction also called recursively. Here is my code i am trying.

this.myArray = Array(2).fill(undefined);
  StartFunction(len: number) {
    console.info('in StartFunction ', len);
    this.SubFunction_1(len);
    this.SubFunction_2(len);    
    if (len > 0) {
      this.myArray.pop();
      this.StartFunction(this.myArray.length);
    }
  }
  SubFunction_1(input: number) {
    console.warn('in SubFunction_1 ', input);
  }
  async SubFunction_2(input: number) {
    console.error('in SubFunction_2 ', input);
    if (input > 0) {
      input--;
      //     const promise = new Promise((resolve, reject) => {
      setTimeout(() => {
        this.SubFunction_2(input);
        //         resolve('getData completed ' + input);
      }, 1000);
      //       // const data = await promise;
      //       // console.log(data);
    }
  }

I want to execute functions in order and wait for SubFunction_2 to complete before proceeding further. Also created stackblitz for the same

https://stackblitz.com/edit/angular-v7ycuk?file=src%2Fapp%2Fapp.component.ts

Tried few things (commented) but could not achieve this. Suggestions ?


Solution

  • Your sub functions should return promises, try the following:

    async SubFunction_2(input: number) {
        return new Promise((resolve, reject) => {
            console.error('in SubFunction_2 ', input);
            if (input > 0) {
                input--;
                setTimeout(() => {
                    this.SubFunction_2(input).then(resolve).catch(reject);
                }, 1000);
            } else {
                resolve('function completed');
            }
        });
    }
    

    Edit to call from the function you provided:

    StartFunction(len: number) {
        console.info('in StartFunction ', len);
        this.SubFunction_1(len);
        this.SubFunction_2(len).then((result) => {
          console.log(result);
          if (len > 0) {
            this.myArray.pop();
            this.StartFunction(this.myArray.length);
          }
        }).catch((error) => {
          console.error('Error:', error);
        });
      }