Introduction to the control process using Callback in JavaScript

  • 2020-05-17 04:44:11
  • OfStack

The ubiquitous callback in javascript is a disaster for process control, with obvious disadvantages:

1. Without explicit return, it is easy to generate redundant processes and the bug generated thereby.
2. Causes code to be infinitely nested and difficult to read.

Here's how to avoid these problems.

The first problem is a habit problem. When you use callback, you often forget to use return. This is especially true when you use coffee-script (although it collects the last data as a return value when it is compiled into javascript, this return value does not necessarily represent your original intention). Take a look at the following example.


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" style of code, we obviously don't want the subsequent code in the method a to be executed if something goes wrong, but we don't want to use throw to kill the whole process, so the code above will produce bug.

One solution is to honestly write if... else... , but I prefer the following:


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 return is used here as a process control rather than if... else... Less code, but more clarity.

The second problem is born in the womb and is difficult to eradicate.

A good way to make your code more logical is to use a flow control module. async, for example, is a good module that provides a series of 1 interfaces, including iterations, loops, and conditional statements. It even includes a queue system. The following example shows the pros and cons of the two ways of writing a name


#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?


Related articles: