0

I have learn the asynchronous process.

In my understanding,

  1. synchronous codes => is stacked and consumed
  2. asynchronous codes => first, go to the webapis, wait for a stack being empty, and consumed by going through the event loop

so, I made one simple code

///class definition///
class Works {
  constructor(){
     this.work = []
   }

   async getWork(){
     const res = await axios.get("....url.....");
     this.work = res.data
     console.log(this.work)
   }
}

///run///
const check = new Works('accounting');
console.log(check); 
check.getWork();

Now the problem is,

in my thought, the result would be

console.log(check) <--- {work : []}
check.getWork(); <---{work:[{...},{...},.....]}

but the result is

console.log(check) <----{work:[{...},{...},.....]}
check.getWork(); <---{work:[{...},{...},.....]}

Why....

I thought that console.log(check) is synchronous one so that the "work" array wasn't updated at this juncture.

Could anyone tell me the reason?

  • Try not to use the console for debugging, especially when working with async actions. Your browser has a mature JavaScript debugger built-in which is much better at differentiating the state of data at the time you're looking at it – Phil Jul 13 '20 at 03:04
  • thanks. your comment helps me. you mean I have to use javascript "debugger" right? – Anderson Kim Jul 13 '20 at 05:25
  • You don't _"have to"_ but it's much better for inspecting your variables at certain points in time. The console is not so good as it updates live with changes – Phil Jul 13 '20 at 05:29

0 Answers0