注册为回调的命名箭头函数的正确语法是什么?

问题描述 投票:0回答:2

我无法理解如何替换注册为回调的函数声明。此代码段按预期方式工作:

const http = require('http');
const fs = require('fs');
const url = require('url');
const ct = { 'Content-Type': 'text/html' };

http.createServer((req, res) => {

  let q = url.parse(req.url, true);
  if (q.pathname === "/") {
    fs.readFile('./index.html', renderIndex);
  }

function renderIndex(err, data) {
    if (err) throw err;
    res.writeHead(200, ct);
    console.log("Rendering index");
    return res.end(data);
  }
}).listen(8080)

但是,我想知道是否可以将renderIndex声明重构为箭头函数。

我从测试中知道,函数表达式不起作用。所以这是不可能的:

...
const renderIndex = function (err, data) {
    if (err) throw err;
    res.writeHead(200, ct);
    console.log("Rendering index");
    return res.end(data);
  }
...

所以也不是:

...
const renderIndex = (err, data) => {
    if (err) throw err;
    res.writeHead(200, ct);
    console.log("Rendering index");
    return res.end(data);
  }
...

但是有没有一种有效的箭头函数语法可以使我将renderIndex注册为fs.readFile('./index.html', renderIndex);中的回调……也许也可以重构该行?

谢谢!

javascript node.js function syntax arrow-functions
2个回答
0
投票

您难道不只是将它用作匿名函数吗?

http.createServer((req, res) => {
  let q = url.parse(req.url, true);
  if (q.pathname === "/") {
    fs.readFile('./index.html', (err, data) => {
      if (err) throw err;
      res.writeHead(200, ct);
      console.log("Rendering index");
      return res.end(data);
    });
  }
}).listen(8080)

0
投票

我认为如果将函数定义移到使用它的行之前,它将起作用。如果是我的代码,则将函数定义移到包含函数之外,如下所示:

const http = require('http');
const fs = require('fs');
const url = require('url');
const ct = { 'Content-Type': 'text/html' };

const renderIndex = res => (err, data) => {
  if (err) throw err;
  res.writeHead(200, ct);
  console.log("Rendering index");
  return res.end(data);
}

http.createServer((req, res) => {

  let q = url.parse(req.url, true);
  if (q.pathname === "/") {
    fs.readFile('./index.html', renderIndex(res));
  }
}).listen(8080)

[这里,我已将定义移到包含函数之外,并对其进行了咖喱处理,因此我可以在将其用作回调之前将res传递给它。


0
投票

函数定义提升仅在函数声明中发生,而在函数表达式中不发生。

移动上面的函数表达式,以便在作为回调传递之前已对其进行定义

const renderIndex = (err, data) => {
    if (err) throw err;
    res.writeHead(200, ct);
    console.log("Rendering index");
    return res.end(data);
  }

 let q = url.parse(req.url, true);
  if (q.pathname === "/") {
    fs.readFile('./index.html', renderIndex);
  }
© www.soinside.com 2019 - 2024. All rights reserved.