readFile()里面的回调函数

时间:2018-06-04 14:10:25

标签: javascript callback

我的问题是关于回叫功能的工作方式。

const fs = require('fs');

let fileContents = 'initial value';
fs.readFile('file.txt', 'utf-8',function(error,res){
    fileContents = res;
    console.log(fileContents);
})

因此,当fs.readFile运行时,会调用function(error,res)。但是,如果我的参数为空,为什么fileContents会收到txt文件中的文本? 我假设readFile将读取的值添加到res参数。 这总是这样吗?

另一个问题是,为什么在删除null时会收到error

2 个答案:

答案 0 :(得分:2)

Readfile看起来像这样:

 function readFile(path, cb) {
   try {
   // Some very complicated stuff
   // All fine, call callback:
   path(/*error:*/ null, /*res: */ "somedata");
  } catch(error) {
   path(error, /*res: */ undefined);
 }
}

所以你在callbacks参数中得到的不依赖于它的名字,而是取决于它的位置,所以当你这样做时:

readFile("/..", function(res) { /*...*/ });

res将是readFile传回的错误,如果那个null是一件好事。

答案 1 :(得分:2)

也许花一点时间来试验回调函数。

回调函数只是作为参数传递给另一个函数的函数。在下面的代码中,我声明了我的功能。 myFunc使用另一个函数作为名为callback的函数的参数。在我的函数内部,我调用函数并将myName作为参数传递给回调。这允许我将其他匿名函数声明为参数,我将其作为示例包含在内。调用myFunc时,它会在其本地环境中调用回调。

然后我可以操作传递给回调的数据,并使用传递给myFuncs回调的变量在匿名函数中编写我自己的代码。

在您的示例中,您使用的是readFile,它从文件中检索数据并将其传递给回调函数和/或在出现错误时传递错误。

function myFunc( callback){
    let myName = "Joe Smo";
    callback(myName);
}
/*
Now I can use my function and add another anonymous function to do whatever I want
provided I use the same parameters that are inside my function. 
*/
myFunc(function(name){
    console.log("What's up!"+name);
});

myFunc(function(strangeName){
    console.log(strangeName+" is a strange name.");

});
相关问题