cheungseol / cheungseol.github.io

2 stars 0 forks source link

[Node] 错误优先回调 #13

Open cheungseol opened 6 years ago

cheungseol commented 6 years ago

为了在node 模块和应用中统一平衡、非阻塞的异步控制流,node 采用了错误优先(error-first)的callback 回调形式。这种形式的回调是追溯到 Continuation-Passing Style (CPS)。CPS 中的“continuation function”接受一个函数作为参数,这个参数函数在函数体中其余代码执行完之后运行。这样的方式使得不同的函数能够异步地控制整个应用。

例子,一个标准的错误优先callback例子:

fs.readFile('/foo.txt', function(err, data) {
  // If an error occurred, handle it (throw, propagate, etc)
  if(err) {
    console.log('Unknown Error');
    return;
  }
  // Otherwise, log the file contents
  console.log(data);
});

处理错误的方式

if(err) {
  // Handle "Not Found" by responding with a custom error page
  if(err.fileNotFound) {
    return this.sendErrorMessage('File Does not Exist');
  }
  // Ignore "No Permission" errors, this controller knows that we don't care
  // Propagate all other errors (Express will catch them)
  if(!err.noPermission) {
    return next(err);
  }
}

参考

The Node.js Way - Understanding Error-First Callbacks