![](/img/trans.png)
[英]Can a callback to a finished XmlHttpRequest trigger before the send-function is complete?
[英]function with callback execute callback before function complete
我會編寫以下代碼來練習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 ")
})
您不是在readFile
自己的回調中調用callback ()
,而是在調用readFile
之后調用它,然后僅在完成后才調用其回調function (err,data)
。
您必須在fs.readFile
回調函數中調用callback()。因為fs.readFile
回調函數應在寫有結果或錯誤的asyc函數之后調用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.