elad
elad

Reputation: 196

asyn await class property changes

What the difference between those two? changing isHidden inside a function that been called using await or changing isHidden before and after the asyc function

class X{
  isHidden = true;

  show(){
    this.isHidden = true;

    return new Promise(resolve=>{
        this.isHidden = false;
        // do something
        resolve(true)
    })
  }
  
  async callShow(){
    await show();
  }
}

And

class X{
  isHidden = true;

  show(){
    return new Promise(resolve=>{
       // do something
        resolve(true)
    })
  }
  
  async callShow(){
    this.isHidden = true;
    await show();
    this.isHidden = false;
  }
}

Upvotes: 0

Views: 476

Answers (1)

vaira
vaira

Reputation: 2270

Combined the two examples and added the order of execution.

class X{
  isHidden = true; // execute 1st

  show(){
    this.isHidden = true; // execute 3rd
    return new Promise(resolve=>{
      // do something
      this.isHidden = false; // execute 4th
      resolve(true)
    })
  }
  
  async callShow(){ 
    this.isHidden = true; // execute 2nd
    await show();
    this.isHidden = false; // execute 5th
  }
}
new X().callShow();

There is no difference between 1-4 execution they are synchronous but 5th is asynchronous meaning will only occur when resolve called with true.

Usually resolve here is done when an API response comes, so till API completes, 'await' will stop reaching the 5th execution.

Await it so the code runs sequentially.

Upvotes: 1

Related Questions