Anyways, enough background, I think most people already know these patterns as there have been blog posts from experts such as Stephen Cleary but I wanted to force myself to write these down to better remember the differences and keep list for future reference.
Wrapping non-async code
Modifying return value of async call
Chaining async operations
Call async operation A then call async operation B. The example we use below involves taking two related async operations and combing there result to construct larger domain object.
There is one major difference between ContinueWith and then. Promises automatically unwrap! This greatly reduces the complexity the developer has to consider.
Aggregate many async tasks
Technically chaining async tasks above to form larger object was a type of aggregation but those tasks were done sequentially. This pattern demonstrates running the tasks in parallel and waiting for them all to complete. In the example below imagine you have to fetch a bunch of individual items from the database and add up the value of a property.
Branching Async Tasks/Building Tree
Now for something more complex. This really is just a more advanced application of different techniques above but is more of real-world example than one-off.
In this scenario each task returns an array of items, which is used to generate another array of tasks, and so on until reaching the leaves of tree and then whole object is returned. For the use case imagine two models which are related to each other and the client wants to construct this relationship; however, the service API only returns IDs of the related models. The client must get the parent model, then request the related models and construct the full object.
RemoteNode simulates the response from server which only includes the id’s of the related items; however, the client constructs the full node which includes full references to other nodes.
Again we will compare Task.ContinueWith/Promise.then with Async/Await
Now using async/await
All of the code is from the gists is in working projects you can view or download here: