gpt4 book ai didi

javascript - JS lambda默认返回值

转载 作者:行者123 更新时间:2023-12-03 00:45:58 24 4
gpt4 key购买 nike

我对 Node.js 中 lambda 的默认返回值有点困惑。我找到了这个链接"Arrow Functions" :

Arrow functions can have either a "concise body" or the usual "block body".

In a concise body, only an expression is specified, which becomes the implicit return value. In a block body, you must use an explicit return statement.

var func = x => x * x;                  
// concise body syntax, implied "return"

var func = (x, y) => { return x + y; };
// with block body, explicit "return" needed

这很清楚,但后来我发现了这段 Express 代码,我测试了它默认返回最后一条语句,而不需要使用“return”:

const express = require('express');
const app = express();

app.use('/api/posts', (req, res, next) => {
const posts = [
{
id: 'sdfj234j654j',
title: 'First server-side post',
content: 'This is comming from the server'
},
{
id: '9054jk4ju59u90o',
title: 'Second server-side post',
content: 'This is comming from the server!'
}
];
// this is returned by default and does not require "return "
res.status(200).json({
message: 'Posts fetched succesfully!',
posts: posts
});
});

那么当我使用 block 引号来定义 lambda 时,我需要使用哪一个 return 语句呢?还是有我不知道的异常(exception)情况?

最佳答案

示例中的箭头函数不返回任何内容。然而,它通过调用 .json({/*...*/}) 写入 response,因此它将 json“返回”给客户端。

一个简化的例子:

  setTimeout(() => {
console.log("test");
}, 1);

上面的代码向控制台输出一些内容,尽管箭头函数没有返回任何内容。

关于javascript - JS lambda默认返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53249834/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com