javascript - 我可以在过滤函数之后做一个回调(或类似的东西)吗?
问题描述
我正在实现一个安静的 api 来只用一个本地文件做一些事情:
数据.js:
let store = {
posts: [
{
id: 1,
name: 'Top 10 ES6 Features every Web Developer must know',
url: 'https://webapplog.com/es6',
text: "This essay will give you a quick introduction to ES6. If you don’t know what is ES6, it’s a new JavaScript implementation.",
comments: [
{ text: 'Cruel…..var { house, mouse} = No type optimization at all' },
{ text: 'I think you’re undervaluing the benefit of ‘let’ and ‘const’.' },
{ text: '(p1,p2)=>{ … } ,i understand this ,thank you !' }
]
},
{
id: 2,
name: 'anotherPost',
url: 'https://webapplog.com/es6',
text: "This essay will give you a quick introduction to ES6. If you don’t know what is ES6, it’s a new JavaScript implementation.",
comments: [
{ text: 'Cruel…..var { house, mouse} = No type optimization at all' },
{ text: 'I think you’re undervaluing the benefit of ‘let’ and ‘const’.' },
{ text: '(p1,p2)=>{ … } ,i understand this ,thank you !' }
]
}
]
}
module.exports = store;
例如,这是我如何执行 Post 请求来创建另一个post
:
router.post('/', (req, res) => {
data.posts.push({
id: req.body.id,
name: req.body.name,
url: req.body.url,
text: req.body.text,
comments: [
req.body.comments
]
})
res.send(data.posts)
})
或者这是我删除帖子的方式(实际上,我将其添加到 id 属性以执行此操作,尽管几分钟后我发现它不是必需的,但正因为如此,它不是创建创建的原因这个问题的)
router.delete('/:postId', (req, res) => {
const post_id = req.body.id;
const index = post_id -1;
data.posts.splice(index, 1);
res.send(data.posts)
})
所以当我尝试做 put 路线时,我想出了这个,虽然后来我也发现我可以使用data.posts[index].name = etc...
,但我决定打开这个问题,因为我真的很好奇它是如何工作的(显然,自从以下代码不起作用):
data.posts.filter(post => {
post.id === req.params.postId;
}).then(post => {
post.id = req.body.id,
post.name = req.body.name,
post.url = req.body.url,
post.text = req.body.text,
post.comments = [
req.body.comments
]
})
一旦过滤了正确的帖子,我想做的就是修改该帖子的属性。我已经做了几个月的 javascript,但我一直在盲目地学习教程,并且从未停下来真正了解回调是如何工作的,或者代码是如何不可能的。但是因为我看到类似的代码可以工作(快递中的回调),我想知道是否有人可以给出一些指导。
正如我所说,我已经有了一个简单的解决方案,但我很好奇我怎么能用过滤器功能做这样的事情(或者只是教育我这个东西是如何工作的)
解决方案
由于该Array#filter
方法是同步的并返回过滤后的数组,因此您可以将Array#map
函数链接到它以转换过滤后数组的元素。在代码都是同步的意义上,不需要“回调”或承诺……对于像 map 和 filter 这样的迭代方法,函数参数通常称为“迭代对象”。
因此,对于您的最后一个代码块,您可以简单地执行以下操作:
const filteredAndModifiedPosts = data.posts.filter(post => {
return post.id === req.params.postId;
}).map(post => {
post.id = req.body.id,
post.name = req.body.name,
post.url = req.body.url,
post.text = req.body.text,
post.comments = [
req.body.comments
]
return post
})
推荐阅读
- node-libcurl - Node-libcurl post 比 Request/Axios/Needle 等其他 Node 包花费更多的时间
- python - GeoPy Geocoder 随机不起作用,但有时会
- html - 锚链接内的字体真棒图标在某些屏幕分辨率下变得不可点击
- c# - 在客户端计算机上运行应用程序时出现 C# 数据库错误
- javascript - 从带有 blob 源的视频中绘制时,Canvas 返回空白 URI - Javascript
- python - 多数据单元测试
- javascript - 使用 beforeCreated 时模板不与数据一起呈现
- c# - 在 .net core 的服务容器中捆绑项目的最佳实践
- udp - HEVC 视频的 P 帧可以在流媒体上丢弃吗?
- kentico - 媒体选择 - GUID 字段