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

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

问题描述

所以我对函数(err,数据)回调的工作方式感到困惑,第一个参数是否始终是错误处理程序?

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('\n');
    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天全站免登陆