Chapter 2,"You shouldn't make assumptions about the app state after an await"

In Chapter 2/page 44, you said @icanzilb that: ‘’ You shouldn’t make assumptions about the app state after an await ‘’ what do you mean by that ? if it is possible give me an example to better understand it.

I think that’s a fair question — this is (in my pov) one of the big gotchas of moving to the new async/await syntax. What I meant by this sentence is that the await line can take an arbitrary amount of time - the execution can resume in a millisecond or less but could also take 5 minutes if another piece of code in the app misbehavingly blocks all cooperative threads. So if you have a piece of shared state say and you set it on the line before the await, let’s say a = 10 then you shouldn’t assume a is still 10 after the await as arbitrary code could be executed in the meantime, e.g.:

self.a = 10
await someFunction()
// is self.a still equal to 10? nobody can tell anything could've happened while the execution was suspended on the line before

I hope that clears the sentence a bit, thanks for chiming in here to discuss

1 Like

But why I couldn’t assume that a is = 10 after the await. I set it before the await, so it will be initialize before the await. or do you mean that the await function can run before the initialization of a ?

One more thing I notice. this means that if a is changed in another piece of code at this point, we can’t assume that it’s still equal 10. because it meat be executed before finishing the await function. But if a is not changed in another piece of code I can still assume that a is equal to 10 is that right ?

thanks for replying @icanzilb

Oh yes, of course - if you don’t change a anywhere else in other function that potentially might run during you’re awaiting in the code above, then of course a will be 10. The comment is really just for the situation when some other code → might ← potentially run while the first code is suspended.

Now that I re-read the text I don’t think this is very clearly said — I really have to re-word that to say that it’s really only about a situation when another code → might ← run in-between.

2 Likes

thanks for replying :heart: