JS lambda 默认 return 值
JS lambda default return value
我对 node.js 中 lambda 的默认 return 值有点困惑。我发现这个 link "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 是最后一条语句,而无需使用 "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
});
});
那么当我使用块引号定义它们时,我需要在 lambdas 上使用 return 语句是哪一个?还是有我不知道的例外情况?
您示例中的箭头函数没有 return 任何内容。然而,它通过调用 .json({ /*...*/})
写入 res
ponse,因此它类似于 "returns" 到客户端的 json。
一个简化的例子:
setTimeout(() => {
console.log("test");
}, 1);
上面的代码向控制台输出了一些东西,尽管没有从箭头函数中得到 returned。
我相信您标记为 'returned by default' 的任何内容实际上都没有得到 returned。函数 returns undefined
,就像任何没有 return 语句的函数一样。在 app.use
中,只要遇到特定路线,就会调用该函数,仅此而已。 res.status
仅写入网络,不 returning 任何值。
我对 node.js 中 lambda 的默认 return 值有点困惑。我发现这个 link "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 是最后一条语句,而无需使用 "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
});
});
那么当我使用块引号定义它们时,我需要在 lambdas 上使用 return 语句是哪一个?还是有我不知道的例外情况?
您示例中的箭头函数没有 return 任何内容。然而,它通过调用 .json({ /*...*/})
写入 res
ponse,因此它类似于 "returns" 到客户端的 json。
一个简化的例子:
setTimeout(() => {
console.log("test");
}, 1);
上面的代码向控制台输出了一些东西,尽管没有从箭头函数中得到 returned。
我相信您标记为 'returned by default' 的任何内容实际上都没有得到 returned。函数 returns undefined
,就像任何没有 return 语句的函数一样。在 app.use
中,只要遇到特定路线,就会调用该函数,仅此而已。 res.status
仅写入网络,不 returning 任何值。