带有回调的函数在函数完成前执行回调

时间:2017-06-20 05:41:29

标签: javascript node.js asynchronous callback

我在javascript中使用回调编写以下代码来练习函数。

fs = require('fs');

function funcWithCallback(callback) {

  fs.readFile('YouBikeTP.txt', 'utf8', function (err,data) {
  if (err) {
    return console.log(err);
  }
  console.log(data.length);
  });
  callback();
}

funcWithCallback(function(){
  console.log("string in callback ")
})

代码的目的是尝试控制方法执行的顺序。回调"中的字符串"字符串应该在打印文本文件的长度后打印,但是当我运行此代码时,结果将是:

>> "string in callback"
>> 91389 //the length of YouBikeTP.txt

这不是我预期的结果。 应该是

 >> 91389 //the length of YouBikeTP.txt
 >> "string in callback"

谁能告诉我为什么在funcWithCallback(回调)完成之前调用回调函数?我是否误解了回调函数的含义?

3 个答案:

答案 0 :(得分:4)

将您的代码更改为:

原因:您在readFile中定义为回调的函数是异步回调。它不会立即执行,而是在文件加载完成时执行。因此,您需要在完成异步回调的console.log之后调用主回调函数。

fs = require('fs');

function funcWithCallback(callback) {

   fs.readFile('YouBikeTP.txt', 'utf8', function (err,data) {
      if (err) {
          return console.log(err);
      }
      console.log(data.length);
      callback(); //calling the main callback after the async callback console logs
   });

}

funcWithCallback(function(){
    console.log("string in callback ")
})

答案 1 :(得分:1)

你没有在callback ()自己的回调中调用readFile,只是在调用readFile之后调用它,然后在完成后调用它的回调function (err,data)

答案 2 :(得分:1)

你必须在fs.readFile回调函数中调用callback()。因为在用结果或错误写入asyc函数之后应该调用回调。