How to Use Callback in JavaScript
This article mainly introduces the Callback control process in JavaScript. This article describes some problems of callback and the optimized coding method and provides code examples. For more information, see
Callback, which is everywhere in javascript, is a disaster for process control and has obvious disadvantages:
1. There is no explicit return, which is prone to redundant processes and bugs.
2. The code is infinitely nested and hard to read.
Next, let's talk about how to avoid the above problems.
The first problem is a habit. When using callback, people often forget to use return, this is especially true when coffee-script is used (although it collects the final data as the return value during compilation into javascript, this return value does not necessarily represent your original intention ). Let's take a look at the example below.
The Code 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, it is clear that we do not want the subsequent code in method a to be executed when an error occurs, but I don't want to use throw to let the whole process go (it must be cool to die ~), Then the above Code will generate a bug.
One solution is to write if... else... honestly, but I prefer the following:
The Code 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)
The return values in javascript asynchronous methods are mostly useless. Therefore, return is used as a process control role, which is clearer than if... else.
The second problem is that it is difficult to eradicate the problem.
A good method is to use some process control modules to make the code more organized. For example, async is a good module and provides a series of interfaces, including iteration and loop, and some condition statements, even including a queue system. The following example shows the advantages and disadvantages of table names.
The Code 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)->
Which one will you choose.