理解 JavaScript 标准的回调模式( CPS )

Asynchronous programming does not use function return values to denote that a function is

fi nished. Instead it uses the continuation-passing style (CPS):


Continuation-passing style (CPS) is a style of programming in which control is

passed explicitly in the form of a continuation. (…)


A function written in continuation-passing style takes as an extra argument
an explicit “continuation,” that is, a function of one argument. When the CPS

function has computed its result value, it “returns” it by calling the continuation

function with this value as the argument.

Wikipedia — http://en.wikipedia.org/wiki/Continuation-passing_style


This is a style in which a function invokes a callback after the operation is complete so that your
program can continue. As you will see, JavaScript lends itself to this type of programming. Here is

an example in Node that involves loading a fi le into memory:


var fs = require('fs');


fs.readFile('/etc/passwd', function(err, fileContent) {
if (err) {
throw err;
}
console.log('file content', fileContent.toString());

});


Here, you are passing an anonymous inline function as the second argument of the fs.readFile
function, and you’re making use of the CPS, because you are continuing the execution of the
program inside that function.
As you can see here, the fi rst argument to the callback function is an error object, which will have an
instance of the Error class if an error occurs. This is a common pattern in Node when using CPS.


你可能感兴趣的:(理解 JavaScript 标准的回调模式( CPS ))