Home >Web Front-end >JS Tutorial >Introduction to using Callback control flow in JavaScript_javascript skills
The callbacks that can be seen everywhere in JavaScript are a disaster for process control, and the shortcomings are obvious:
1. Without an explicit return, it is easy to produce redundant processes and the resulting bugs.
2. The code is infinitely nested and difficult to read.
Let’s talk about how to solve and avoid the above problems.
The first problem is a matter of habit. When using callback, people often forget to use return. This is especially true when using coffee-script (although it will collect the final result by itself when compiled into javascript). The data is used as the return value, but this return value does not necessarily represent your original intention). Take a look at the example below.
b = ->
console.log 'I am a callback'
a('error', b)
In this so-called "error first" coding style, obviously we don't want the subsequent code in method a to still be executed when an error occurs, but we don't want to use throw to make the entire process hang (it has to be graceful even if it happens) Damn it~), then the above code will generate bugs.
One solution is to write if...else... honestly, but I prefer the following approach:
b = ->
console.log 'I am a callback'
a('error', b)
Most of the return values in JavaScript asynchronous methods are useless, so return is used here to act as a process control, which is less code than if...else..., but more clear.
The second problem is caused in the mother’s womb and is difficult to eradicate.
A good way is to use some flow control modules to make the code more organized. For example, async is a good module that provides a series of interfaces, including iteration, looping, and some conditional statements, and even includes A queuing system. The following examples can illustrate the advantages and disadvantages of the two writing methods
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 will you choose?