我将编写以下代码来练习在 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”应该在打印完文本文件的长度后打印出来,但是当我运行这段代码时,结果将是:
>> "string in callback"
>> 91389 //the length of YouBikeTP.txt
这不是我期望的结果。 应该是
>> 91389 //the length of YouBikeTP.txt
>> "string in callback"
谁能告诉我为什么回调函数会在 funcWithCallback(callback) 完成之前被调用?我是否误解了回调函数的含义?
最佳答案
将您的代码更改为:
原因:您在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 ")
})
关于javascript - 带有回调的函数在函数完成之前执行回调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44644658/