📎 Webclip
Patterns for Asynchronous Programming with Promises
The post lays out a few ways to handle asynchronous operations with promises. It starts with parallel work, either waiting for all operations before running synchronous steps in order, or attaching a callback to each promise so synchronous work happens as soon as each operation finishes. It then shows two sequential patterns, one built with each and one with reduce, both chaining each async step off the previous one and gathering results in an array.
Reading notes#
- Promises are presented as the main tool for asynchronous programming for now, especially when handling multiple operations.
- The examples use Q for promises and Underscore or Lodash for map, each, and reduce.
- For parallel async work followed by ordered synchronous processing, map creates the promise array and Q.all waits for completion before looping through the results.
- For parallel async work with unordered synchronous follow-up, map is used with a callback that calls then immediately after each async operation.
- For sequential async work, each chains promises one by one, storing the chain in a promise variable.
- The reduce version passes the promise chain as the memo and uses the same chaining approach.
- Both sequential patterns use a blank resolved promise to start the chain.
- Both sequential patterns push new values into an array and return that array at the end.
