I was pointed to a very good article providing a very good overview of the different possibilities handling asynchronous code execution in JavaScript:
- Callbacks
- Promises
- RxJS Observables
- async/await
Article summary
Callbacks | Promises | Observables | async/await | |
ES6 feature, but libraries available for ES5; “promise” a certain value in the future | working with streams of data instead of single value (=> abstraction!); operators for data manipulation and control | ES8 writing asynchronous code like synchronous one instead of code “blocks” async always return automagically a promise, wait waits for promise resolution | ||
advantages | postpone (without blocking) code execution; difficult error handling | resolve/reject provides better error handling; chaining of promise handling | powerful unified syntax and mechanism, error handling completion handling (eventually – based on observables) | try-catch for error handling |
disadvantages | extensive nesting, “callback hell” | one asynchronous operations with each promise | operator syntax might be confusing, RxJS library obligatory | |
suggested usage | single asychronous operations | single value HTTP requests are fine but not for operations not ending after one “promised value” like click events (you can just react on each single click) | stream of data | synchronous handling of promises |