首页 > 解决方案 > 我可以在过滤函数之后做一个回调(或类似的东西)吗?

问题描述

我正在实现一个安静的 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,但我一直在盲目地学习教程,并且从未停下来真正了解回调是如何工作的,或者代码是如何不可能的。但是因为我看到类似的代码可以工作(快递中的回调),我想知道是否有人可以给出一些指导。

正如我所说,我已经有了一个简单的解决方案,但我很好奇我怎么能用过滤器功能做这样的事情(或者只是教育我这个东西是如何工作的)

标签: 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
})

推荐阅读