danvk / effective-typescript

Effective TypeScript 2nd Edition: 83 Specific Ways to Improve Your TypeScript
https://effectivetypescript.com
Other
1.53k stars 226 forks source link

Suspected error in Item 25: Use async Functions Instead of Callbacks for Asynchronous Code #14

Closed liby closed 2 years ago

liby commented 2 years ago

Chapter 25 has the following description:

image

Playground

In fact, requestStatus will be set to success and then to loading regardless of whether the profile is cached or not.

danvk commented 2 years ago

You're seeing consistent behavior because your implementation of fetchURL is synchronous. If you make it async (but without declaring it async):

function fetchURL(url: string, cb: (response: string) => void) {
  setTimeout(() => {
    cb(url);
  }, 10);
}

Then you can call getUser("test") twice and observe different behaviors.

Here's an updated version of your playground link.