I've been tasked with developing a WebApp using Angular, but I'm facing a challenge as the project involves Typescript and asynchronous programming, which are new to me. The prototype already exists, and it includes a handshake process that consists of calculations and HTTP requests. All functions, even those performing calculations, return a Promise that resolves or rejects based on the outcome.
The functions are connected in a long chain using .then
, handling errors along the way. However, this implementation seems complex, and I'm unsure about what's happening behind the scenes:
this.startHandshake()
.then((buf) => this.calculateSomthing(buf)
.then((buf2) => http.sendData(buf2)
..., // this goes on many levels
(e:Error) => this.handleError(e)),
(e:Error) => this.handleError(e))
.catch((e: Error) => { /* Error Handling */ });
My questions are:
- Is this coding pattern common for similar problems?
- I've heard that Promises are executed in a single-threaded manner. What does this mean for Promises involving only calculations? When does the function within the Promise execute - immediately, queued until the original code finishes, or scheduled by the JavaScript engine?
- I'm thinking of writing some functions synchronously but need a way to handle errors. Using exceptions doesn't seem compatible with Promises.
- Would using async/await make the code more readable in my case? How would error handling work with async/await, and can it be combined with exceptions?