我正在实现一个restful api来仅使用本地文件来做一些事情:
data.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 好几个月了,但我总是盲目地遵循教程,从未停下来实际学习回调是如何工作的,或者该代码是如何不可能的。但是因为我看到类似的代码可以工作( express 中的回调),所以我想知道是否有人可以提供一些指导。
正如我所说,我已经有了简单的解决方案,但我很好奇如何使用过滤功能实现类似的功能(或者只是教育我这个东西是如何工作的)
最佳答案
由于 Array#filter 方法是同步的并返回过滤后的数组,因此您可以将 Array#map 函数链接到它以转换过滤后的元素大批。不需要“回调”或 promise ,因为代码都是同步的......对于像映射和过滤器这样的迭代方法,函数参数通常称为“迭代器”。
因此,对于最后一个代码块,您可以简单地执行以下操作:
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
})
关于javascript - 我可以在过滤器函数之后执行回调(或类似的操作)吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58699095/