async-then
Manipulate asynchronous operations
Work with Node-style callbacks in a safe way. The API is modeled after Promises, while async-then doesn't need (or support) promises.
NB: This is a proof-of-concept of applying Promise idioms to callbacks. This package won't likely be supported.
Features
Waterfall flow
Using chain() and then(), you'll be able to run async operations one after the other, giving the result on an operation to the next operation and so on.
{
For comparison, here it is without async-then:
{fs}
Error control
Notice in the example above, error handling (if (err) return next(err)
) is absent. Errors will skip through then() steps, moving onto the next catch() or end() instead.
At a glance
-
No promises - async-then works with Node-style callbacks (
err, result
), and does not support promises. It lets you work these kinds of operations in a way you would with Promises/A+ without actually using promises. -
No wrappers - unlike other solutions like co v3, there's no need to wrap your callback-style functions into thunks or promise-generators.
-
Error catching - no need for extraneous
if (err) throw err
. Error flow is managed like promises with catch().
API
chain
chain()
Starts a chain. Compare with Promise.resolve()
or any other promise. Returns an object with then(), catch() and end() methods.
var chain = { ) }
chain().then
chain().then(fn)
Continues a chain; queues up another function to run when previous then()
calls complete. In the asynchronous form, the function fn
should accept two parameters: result
, next
.
Async
When fn
accepts 2 parameters (result
, next
), it's invoke asynchronously. The parameter result
is the result of the previous operation. next
is a function that should be invoked as a callback.
Synchronous form
When fn
only accepts 1 parameter (result
), it's invoked synchronously. Whatever its return value will be the value passed to the next then()
in the chain.
Errors
Th fn
function can either throw
an error, or invoke next
with an error. All errors will skip through the subsequent then()
steps; it skips onto the next catch() or end().
chain().catch
chain().catch(fn)
Catches errors. It works like then().
If a catch() operation succeeds (meaning it didn't throw
an error, or invoke next(err)
), it'll continue onto the next then() or end().
chain().end
chain().end(fn)
Runs the chain. Without calling .end(fn)
, the chain will not be called. The parameter fn
is a callback that takes Node-style arguments: err
, result
.
all
all(callbacks, next)
Runs multiple async operations in parallel. Compare with Promise.all()
.
var all =
Thanks
async-then © 2016+, Rico Sta. Cruz. Released under the MIT License.
Authored and maintained by Rico Sta. Cruz with help from contributors (list).
ricostacruz.com · GitHub @rstacruz · Twitter @rstacruz