Angular Async not apearing in order

This has nothing to do with Angular, this is how JavaScript works.

See this vanilla JS version:

class AppComponent  {
  async main() {
    await this.one();
    await this.two();
    await this.three();
  }

  async one() {
    setTimeout(() => { 
      console.log('one finished');
    }, 5000);
  }

  async two() {
    setTimeout(() => { 
      console.log('two finished');
    }, 1000);
  }

  async three() {
    setTimeout(() => { 
      console.log('three finished');
    }, 4000);
  }
}

let x = new AppComponent();
x.main();

I think you are expecting one() to take 5000 seconds, two() to take 1000 seconds and three() to take 4000 seconds to execute.

But Actually, they execute instantaneously, it set a timeOut and return the control flow to the caller.

Since console.logs are inside the timeOut functions, based on the timeout intervals.

You can create a setTimout function and await it on one(), two() and three()

async function setTimeouAsync(fn, ms) {
    return new Promise(resolve => {
        setTimeout(resolve, ms);
    }).then(() => {
        fn();
    });
}


@Component({
  selector: "my-app",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.css"]
})
export class AppComponent {
  name = "Angular " + VERSION.major;

  async main() {
    await this.one();
    await this.two();
    await this.three();
  }

  async one() {
    await setTimeouAsync(() => {
      console.log("one finished");
    }, 5000);
  }

  async two() {
    await setTimeouAsync(() => {
      console.log("two finished");
    }, 1000);
  }

  async three() {
    await setTimeouAsync(() => {
      console.log("three finished");
    }, 4000);
  }

  constructor() {
    this.main();
  }
}

An example can be found HERE

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top