The ubiquitous callback in JavaScript is a disaster for process control, and the drawbacks are obvious:
1. No explicit return, easy to generate redundant processes, and the resulting bug.
2. Cause code Unlimited nesting, difficult to read.
Here is how to solve the problem of avoiding the above.
The first problem is a habit problem that often forgets to use return when using callback, especially when using coffee-script (although it collects the final data as a value when compiling JavaScript). But this return value does not necessarily represent your original intention. Take a look at the example below.
Copy Code code as follows:
A = (err, callback)->
Callback () If Err?
Console.log ' You'll-me '
b =->
Console.log ' I am a callback '
A (' error ', b)
In this so-called "error a" code style, it is clear that we do not want to go wrong when the following code in method A is still being executed, but do not want to use throw to let the whole process hang (die gracefully), then the above code will produce bugs.
One solution is to honestly write if...else ... but I prefer the following approach:
Copy Code code as follows:
A = (err, callback)->
Return callback () if Err?
Console.log ' You'll not ' I '
b =->
Console.log ' I am a callback '
A (' error ', b)
Most of the return values in a JavaScript asynchronous method are useless, so it serves as a process-control role, rather than if...else ... Less code, but more clearly.
The second problem is that it is difficult to eradicate when it comes to the womb.
A good way is to use some process control modules to make the code more organized, such as Async is a good module, providing a series of interfaces, including iterations, loops, and some conditional statements, and even a queue system. The following example can be used as a table name in two ways
Copy Code code as follows:
#normal
A (callback)->
Console.log ' I am the ' I '
Callback ()
Second = (callback)->
Console.log ' I am the second function '
Callback ()
Third = ()->
Console.log ' I am the third function '
The->
Second->
Third ()
# Use Async
Async = require (' async ')
Async.waterfall [
First
Second
Third
], (ERR)->
As a wise you, will choose which one.