Sam*_*000 1 javascript node.js
我正在查看使用"if(err){// code //);"的Node.js代码示例.用于控制其函数输出的语句 - 但是当调用函数时,我没有看到任何传递给它们的东西,就好像"err"参数是由幕后的隐形代码定义的......
以下代码是异步的,并使用SDK中的外部模块,如果需要注意的话.
/* "client.sendEvent" sends the data contained within the variable "message"
to its destination, when this is complete the callback function "printResultFor"
is called and a string is passed to that */
client.sendEvent(message, printResultFor('Message'));
//printResultFor looks like this:
var printResultFor = function (op) {
return function printResult(err, res) {
if (err) console.log(op + ' error: ' + err.toString());
if (res) {
console.log(op + ' status: ' + res.constructor.name);
};
};
}
Run Code Online (Sandbox Code Playgroud)
我的问题是:
和
我确实想知道答案是否在外部模块但我不知道......
(最后注意:我是Javascript和Node的自学新手,我敢打赌这对大多数人来说都是微不足道的,但感谢您提供任何解释和帮助.)
这称为错误第一次回调,它不是语言功能,而是惯例.
正如Fred K. Schott在Node.js中所说的那样- 理解错误优先回调:
回调的第一个参数是为错误对象保留的.如果发生错误,它将由第一个错误参数返回.
回调的第二个参数保留给任何成功的响应数据.如果没有发生错误,则将err设置为null,并且将在第二个参数中返回任何成功的数据.
基本上它说的是,如果通过检查第一个参数你会知道任何错误.
这是任何基于回调的nodejs库的预期行为,您应该设计类似的接口.
| 归档时间: |
|
| 查看次数: |
254 次 |
| 最近记录: |