Callbacks that are everywhere in JavaScript are a disaster for process control, and their disadvantages are obvious:
1. Without an explicit return, it is easy to generate unnecessary processes and bugs caused by them.
2. The code is nested infinitely and difficult to read.
Let’s talk about how to solve and avoid the above problems.
The first problem is a habit problem. When using callback, people often forget to use return. This situation is especially true when using coffee-script (although it collects the last data as the return value when compiled into javascript, this return value does not necessarily represent your original intention). Take a look at the example below.
The code copy is as follows:
a = (err, callback)->
callback() if err?
console.log 'you will see me'
b = ->
console.log 'I am a callback'
a('error', b)
In this so-called "error first" code style, obviously we do not want the subsequent code in method a to be executed when an error occurs, but we do not want to use throw to make the entire process hang up (you have to die gracefully~), so the above code will cause bugs.
One solution is to honestly write if...else..., but I prefer the following:
The code copy is as follows:
a = (err, callback)->
return callback() if err?
console.log 'you will not see me'
b = ->
console.log 'I am a callback'
a('error', b)
Most of the return values in javascript asynchronous methods are useless, so here we use return as a process control role, with less code than if...else... but clearer.
The second problem is that it is difficult to eradicate.
A good way is to use some process control modules to make the code appear more organized. For example, async is a good module that provides a series of interfaces, including iteration, loops, and some conditional statements, and even a queue system. The following examples can be used to describe the advantages and disadvantages of the two ways of writing names.
The code copy is as follows:
#normal
first = (callback)->
console.log 'I am the first function'
callback()
second = (callback)->
console.log 'I am the second function'
callback()
third = ()->
console.log 'I am the third function'
first ->
second ->
third()
# use async
async = require('async')
async.waterfall [
first,
second,
third
], (err)->
As a wise person, which one would you choose?