了解函数(错误、数据)回调 [英] Understanding function (err, data) callbacks

查看:48
本文介绍了了解函数(错误、数据)回调的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我对 function(err, data) 回调的工作方式感到困惑,第一个参数总是错误处理程序吗?

So I am confused about how the function(err, data) callback works, is the first argument always an error handler?

如果你有类似函数 (x, y, z, a, b, c) 的剩余参数呢?

What about the remaining arguments if you had something like function (x, y, z, a, b, c)?

fs.readFile 中的数据如何从最上面一行代码传递到最下面一行代码?或者换句话说,fs.readFile 的输出如何放入 data 参数中?

How does the data from fs.readFile pass from the top line of code to the bottom line of code? Or in other words, how does the output of fs.readFile get put into the data argument?

fs.readFile(pathToFile, function (err, **data**) {
    bufferString = **data**.toString();

我可以用函数 (x, y) 和函数 (x, y, z, a, b, c) 替换函数 (err, data)

I could replace function (err, data) with function (x, y) and function (x, y, z, a, b, c)

但只有第二个参数有效(数据和 y),这只是 javascript 回调的语法吗?

But only the second argument works (data and y), is this just the syntax of javascript callbacks?

例如,这是异步读取文件并打印给定文件的行数的工作代码:

For example, this is working code to asynchronously read a file and print out the number of lines given a file:

var fs = require('fs');
var pathToFile = process.argv[2];
var bufferString, bufferStringSplit;

function counter(callback) {
  fs.readFile(pathToFile, function (err, data) {
    bufferString = data.toString();
    bufferStringSplit = bufferString.split('
');
    callback();
  });
}

function logMyNumber() {
  console.log(bufferStringSplit.length-1);
}

counter(logMyNumber);

推荐答案

回调的调用者(在本例中为 readFile 方法)决定将哪些参数传递给回调.您需要声明您的回调以匹配 readFile 所说的它将传递给回调的内容.您可以为参数命名任何您想要的名称(您使用的名称无关紧要),但它们将按照 readFile 决定的顺序获取值.

The caller of the callback (which is the readFile method in this case) decides what arguments are passed to the callback. You need to declare your callback to match what readFile says that it will pass to the callback. You can name the arguments anything you want (the names you use do not matter), but they will get values in the order that readFile decides.

在这种情况下,fs.readFile() 使用代码中的两个参数调用回调,如 callback(err, data).

In this case, fs.readFile() calls the callback with the two arguments you have in your code as in callback(err, data).

以下是来自 node.js 文档的示例:

Here's an example from the node.js docs:

fs.readFile('/etc/passwd', function (err, data) {
  if (err) throw err;
  console.log(data);
});

这篇关于了解函数(错误、数据)回调的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆