Understanding Callback

来源:互联网 发布:入驻淘宝企业店铺2017 编辑:程序博客网 时间:2024/06/18 07:07

Callbacks are just functions that get executed at some later time.

The key to understanding callbacks is to realize that they are used when you don’t know when some async operation will complete, but you do know where the operation will complete — the last line of the async function!

The top-to-bottom order that you declare callbacks does not necessarily matter, only the logical/hierarchical nesting of them. First you split your code up into functions, and then use callbacks to declare if one function depends on another function finishing.

You give readFile a function (known as a callback) that it will call after it has retrieved the data from the file system.
It puts the data it retrieved into a javascript variable and calls your function (callback) with that variable.
In this case the variable is called fileContents because it contains the contents of the file that was read.

var fs = require('fs')var myNumber = undefinedfunction addOne(callback) {  fs.readFile('number.txt', function doneReading(err, fileContents) {    myNumber = parseInt(fileContents)    myNumber++    callback()  })}function logMyNumber() {  console.log(myNumber)}addOne(logMyNumber)

Now the logMyNumber function can get passed in as an argument that will become the callback variable inside the addOne function. After the operation (readFile) is done, the callback variable will be invoked (callback()).

Only functions can be invoked, so if you pass in anything other than a function it will cause an error.

When a function gets invoked in javascript the code inside that function will immediately get executed.
当JavaScript中的函数被调用时,该函数内的代码将立即被执行。

In this case our log statement will execute since callback is actually logMyNumber(). Remember, just because you define a function it doesn’t mean it will execute. You have to invoke a function for that to happen.
请记住,你只是定义了一个函数的话,它并不意味着会被执行。 你必须调用一个函数才能触发它。

To break down this example even more, here is a timeline of events that happen when we run this program:

  1. The code is parsed, which means if there are any syntax errors they would make the program break. During this initial phase, fs and myNumber are declared as variables while addOne and logMyNumber are declared as functions. Note that these are just declarations. Neither function has been called nor invoked yet.
  2. When the last line of our program gets executed addOne is invoked with the logMyNumber function passed as its callback argument. Invoking addOne will first run the asynchronous fs.readFile function. This part of the program takes a while to finish.
  3. With nothing to do, node idles for a bit as it waits for readFile to finish. If there was anything else to do during this time, node would be available for work.
  4. As soon as readFile finishes it executes its callback, doneReading, which parses fileContents for an integer called myNumber, increments myNumber and then immediately invokes the function that addOne passed in (its callback), logMyNumber.

Perhaps the most confusing part of programming with callbacks is how functions are just objects that can be stored in variables and passed around with different names. Giving simple and descriptive names to your variables is important in making your code readable by others. Generally speaking in node programs when you see a variable like callback or cbyou can assume it is a function.

You may have heard the terms ‘evented programming’ or ‘event loop’. They refer to the way that readFile is implemented(被使用). Node first dispatches(调用) the readFile operation and then waits for readFile to send it an event that it has completed. While it is waiting node can go check on other things. Inside node there is a list of things that are dispatched but haven’t reported back yet, so node loops over the list again and again checking to see if they are finished. After they finished they get ‘processed’, e.g. any callbacks that depended on them finishing will get invoked.

Here is a pseudocode version of the above example:

function addOne(thenRunThisFunction) {  waitAMinuteAsync(function waitedAMinute() {    thenRunThisFunction()  })}addOne(function thisGetsRunAfterAddOneFinishes() {})

Imagine you had 3 async functions a, b and c. Each one takes 1 minute to run and after it finishes it calls a callback (that gets passed in the first argument). If you wanted to tell node start running a, then run b after a finishes, and then run c after b finishes’ it would look like this:

a(function() {  b(function() {    c()  })})     [a minute later]        [a minute later]a() ------------------> b() ------------------> c()

When this code gets executed,

  • a will immediately start running, then a minute later a will finish and call b
  • Then a minute later b will finish and call c
  • And finally 3 minutes later node will stop running since there would be nothing more to do.

There are definitely more elegant ways to write the above example, but the point is that if you have code that has to wait for some other async code to finish then you express that dependency by putting your code in functions that get passed around as callbacks.

The design of node requires you to think non-linearly. Consider this list of operations:

read a file
process that file

If you were to turn this into pseudocode you would end up with this:

var file = readFile()
processFile(file)

This kind of linear (step-by-step, in order) code isn’t the way that node works. If this code were to get executed then readFile and processFile would both get executed at the same exact time. This doesn’t make sense since readFile will take a while to complete. Instead you need to express that processFile depends on readFile finishing. This is exactly what callbacks are for! And because of the way that JavaScript works you can write this dependency many different ways:

var fs = require('fs')fs.readFile('movie.mp4', finishedReading)function finishedReading(error, movieData) {  if (error) return console.error(error)  // do something with the movieData}

But you could also structure your code like this and it would still work:

var fs = require('fs')function finishedReading(error, movieData) {  if (error) return console.error(error)  // do something with the movieData}fs.readFile('movie.mp4', finishedReading)

Or even like this:

var fs = require('fs')fs.readFile('movie.mp4', function finishedReading(error, movieData) {  if (error) return console.error(error)  // do something with the movieData})

完结撒花

invoked - 调用

link of 很好的 callback 阐述