Skip to content
Advertisement

Can i do a callback (or something similar) after a filter function?

I am implementing a restful api to do stuff just with a local file:

data.js:

JavaScript

For example here´s how I do a Post request to create another post:

JavaScript

Or here´s how I delete a post (i actually add it the id property in order to do this, although minutes later i found out it wasn´t neccesary, but because of it it wasn´t the reason it came up the creation of this question)

JavaScript

So when I try to do the put route i came up with this, although later i also found out i could just use data.posts[index].name = etc... but I decided to open this question because i have really curiosity in how something can this could work (obviously something similar since the following code does not work):

JavaScript

What am trying to do there is once the correct post has been filtered, then modify the properties of that post. I´ve been doing javascript for months but i have always been blindly following tutorials and never stop to actually learn how callbacks work or how that code is not possible. But because i see similar code to work (callbacks in express), i was wondering if somebody could give some direction.

As i said i already have the simple solution sorted it out but i am very curious in how i could so something like that with the filter function (or just educate me in how this things works)

Advertisement

Answer

Since the Array#filter method is synchronous and returns the filtered array, you can chain the Array#map function to it in order to transform the elements of the filtered array. There’s no need for a “callback” or promise in the sense that the code is all synchronous … for iterative methods like map and filter, the function argument is typically called an “iteratee”.

So for your last code block, you can simply do something like this:

JavaScript
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement