简体   繁体   中英

lodash - chaining filter and forEach

I have the following working code written with lodash, latest version

            _.forEach(_.filter($ctrl.data, ['x', 'y']), function (elem) {
                ...
            });

If I try to transform this into a chain, it will never execute the block code inside forEach .

            _.chain($ctrl.data)
                .filter(['x', 'y'])
                .forEach(function (elem) {
                   ...
                });

Why?

I fixed the problem by using _($ctrl.data) instead of _.chain($ctrl.data) . I read that the main difference here is that the global function from lodash calls _.value() when it has a "terminator function" at the end.

An equivalent using _.chain would be to explicitly call _.value() at before _.forEach() . But still can't figure out what is the problem because, from my point of view, a forEach is a "terminator function".

I just ran into a similar issue. I was using the _(blah) syntax and I was still running into issues.

In my case, the code looked like this:

_(items).forEach((x) => doSomething(x));

It turns out the doSomething was returning a boolean . I guess lodash sees this return value and treats forEach the same as map , not evaluating it. However, I tried tacking on a value() onto the end and I get a value is not a function error at runtime.

In my case, the problem was solved by wrapping the doSomething call:

_(items).forEach((x) => { doSomething(x); });

Seems more like a bug than anything.

This happens because execution of chained methods in lodash is lazy.

From lodash documentation on sequences:

The execution of chained methods is lazy, that is, it's deferred until _#value is implicitly or explicitly called.

That means that following code:

_.chain(['a','b','c'])
    .filter(_.stubTrue)
    .forEach(i => console.log(i))

will not print anything to console unless the sequence will be ended with value() :

_.chain(['a','b','c'])
    .filter(_.stubTrue)
    .forEach(i => console.log(i))
    .value()
a
b
c

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM