回調參數名稱 (Callback parameters name)


問題描述

回調參數名稱 (Callback parameters name)

在這個簡單的node.js代碼中

var fs = require("fs");

fs.readFile('input.txt', function(err, data){
    if(err) console.log(err.toString());
    console.log(data.toString());
});

console.log('End of the program');

編譯器怎麼知道有錯誤會觸發err,而data 會是從文件中讀取的數據嗎?

和參數的順序有關嗎?如果是,我怎麼知道我可以使用多少個參數?

編輯抱歉,沒有正確閱讀文檔。


參考解法

方法 1:

Yes, it's by the order of the arguments.

And you'd know by the documentation.

The callback is passed two arguments (err, data), where data is the contents of the file.

You might also take a look at Node style callbacks under the Node.js Errors docs.

方法 2:

How does the compiler know that err will be triggered if there is an error, and data will be the data read from the file?

Because the code for readFile defines it as such.

Is it related to the order of the argument?

Yes. Just like any other function call.

If yes, how can I know how many arguments I can use?

By reading the documentation (or source code) for the function that calls your callback.

(by MornorPaul RoubQuentin)

參考文件

  1. Callback parameters name (CC BY‑SA 2.5/3.0/4.0)

#javascript #Callback #node.js






相關問題

為什麼我不能在 IE8 (javascript) 上擴展 localStorage? (Why can't I extend localStorage on IE8 (javascript)?)

在 Javascript 中打開外部 sqlite3 數據庫 (Open external sqlite3 database in Javascript)

Javascript:數組中的所有對像都具有相同的屬性 (Javascript: All Objects in Array Have Same Properties)

為什麼我們要在 javascripts 原型中添加函數? (Why do we add functions to javascripts prototype?)

顯示 URL javascript 的最後一部分? (Display the last part of URL javascript?)

Javascript XMLHttpRequest:忽略無效的 SSL 證書 (Javascript XMLHttpRequest: Ignore invalid SSL Certificate)

有沒有辦法測試 console.log 整體 (Is there a way to test for console.log entires)

如何從 javascript 對像中獲取名稱和值到新列表中? (How to get name and values from a javascript object into a new list?)

數據未發布..幫助!html,js,firebase (Data not posting.. Help! html,js,firebase)

使用 Node.js 腳本查看表單數據 (Seeing form data with Node.js script)

使用百分比查找範圍內的值 (find the value within a range using percent)

如何通過 react.js 中的組件傳遞變量或數據? (How to pass varible or data through components in react.js?)







留言討論