[英]How to pass req, res to callBack function?
在 node.js 中,如何為回調 function 傳遞 req、res?
例如,
router.get("/", function (req, res) {
var content = '';
fs.readFile("./json/hello.json", function(err, file)
{
if(err)
res.render("index", {
json: content
});
else
{
content = JSON.parse(file);
res.render("index", {
json: content.name
});
}
});
});
它運作良好。 但是由於縮進很多,代碼很難看。 所以我想這樣做。
router.get("/", function (req, res) {
fs.readFile("./json/hello.json", root_readFileCallBack());
});
function root_readFileCallBack(err, file) {
if (err) {
res.render("index", {
json: content
});
}
else {
content = JSON.parse(file);
res.render("index", {
json: content.name
});
}
}
上面的代碼更容易閱讀。 但這會導致無法從“res”變量中找到“render”的錯誤。
我嘗試將 req, res 作為參數傳遞,但效果不佳。
如何將 req、res 傳遞給回調函數?
Create a closure function, the function will return a callback function for readFile
function, and the function's param is res
object.
router.get("/", function (req, res) {
fs.readFile("./json/hello.json", root_readFileCallBack(res));
});
function root_readFileCallBack(res) {
return function (err, file) {
if (err) {
res.render("index", {
json: content
});
}
else {
content = JSON.parse(file);
res.render("index", {
json: content.name
});
}
}
}
@hoangdv 有一個很好的答案,在實踐中很常用。 創建這樣的工廠函數是一個有用的學習技巧。
這是 go 實現您想要的另一種方法。
router.get("/", function (req, res) {
const callback = (err, file) => root_readFileCallBack(err, file, res)
fs.readFile("./json/hello.json", callback);
});
function root_readFileCallBack(err, file, res) {
if (err) {
res.render("index", {
json: content
});
}
else {
content = JSON.parse(file);
res.render("index", {
json: content.name
});
}
}
基本上我們讓 root_readFileCallBack() 接受一個 res 參數,然后在 router.get() 中我們包裝 root_readFileCallBack 以稍微修改它的行為 - 具體來說,每當調用我們的新回調時,我們都會讓 res 自動傳入。
這是使用箭頭 function ,但正常的 function 也可以正常工作。
Append req/res arguments 到回調 function。
router.get("/", function (req, res) {
fs.readFile("./json/hello.json", root_readFileCallBack.bind(this, req, res));
});
function root_readFileCallBack(req, res, err, file) {
if (err) {
res.render("index", {
json: content
});
}
else {
content = JSON.parse(file);
res.render("index", {
json: content.name
});
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.