1

I have 3 asynchronous typescript methods, which are to be executed in parallel as i have shown below. I want to execute the last function after all the 3 of them had finished the execution . How could i accompany this.

this.getTimeLecs(prevTimeStartStr , nowTimeStartStr).then((result) => {
  // console.log(result);
  this.previousData = result;
});
this.getTimeLecs(nowTimeStartStr, nextTimeStartStr).then((result) =>{
  this.currentData = result;
});
this.getTimeLecs(nextTimeStartStr , nextTimeEnd ),then(result) => {
  this.nextData = result;
};
finalFunction();

2 Answers 2

2

With async/await this can be achieved.

export class AsyncAwaitExample {
  constructor() {
  }
  getTimeLecs(str1, str2) {
    return Promise.resolve(str1 + ":" + str2).then(v => console.log(v));
  }
  async getTimeALL() {
    await Promise.all([
      this.getTimeLecs(10, 20),
      this.getTimeLecs(20, 30),
      this.getTimeLecs(30, 40)]
    );
    this.finalCall();
  }
  finalCall() {
    console.log('final call');
  }
}

let example = new AsyncAwaitExample();
example.getTimeALL();

Here

 await Promise.all([
          this.getTimeLecs(10, 20),
          this.getTimeLecs(20, 30),
          this.getTimeLecs(30, 40)]
        );

waits for all the promises to get resolved and then calls finalCall() method. to check whether this works or not, remove await from the above code and see the results in console. Check the Demo, to see it in action.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks....someone please give due credit to him by up voting the answer
0

I have encountered this situation a few times and a very simple method is to use a counter at the top of the scope. Then at each callback, increment the counter and if it is equal to the total amount of calls, the function is ready to be called.

However, there exists far more glamorous methods such as the async library, which is much better because you can add more functions without re-evaluating the counter and changing each test.

1 Comment

thanks for the solution...but i would prefer solution from async library

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.