仅将 .map() 方法用于副作用是否合法?

Is it legit to use .map() method only for side-effects?

使用高阶函数(如 Array.map())进行循环来执行一些副作用是否合法(或良好做法)?

这主要是一个理论问题,因为我注意到有时我发现(或自己执行)一些使用 .map() 方法的循环,如下所示:

let myObject = {...}
let myItemsArray = [ ... , ... ]

myItemsArray.map( (item, index) => {
    // do some side effect for ex: 
    myObject.item[index] = item
}

但我知道这个map()方法实际上是returns一个数组。所以调用 myItemsArray.map() 就像我返回一个数组而不将其分配给任何变量。

那么问题来了,这是合法的吗?我应该避免这种情况并使用经典的 for() 循环还是 .forEach() 方法?

附带问题:我问这个的原因之一是因为我需要在异步函数上执行一些循环,所以涉及到 promises 和 await 运算符,我记得forEach() 循环在异步函数上并不理想,但想知道原因。

So the question, is this legit? Should I avoid this and use a classic for() loop or a .forEach() method?

如果您没有从 map 函数返回任何内容,那么您应该改用 forEach。您最终得到了相同的结果,但您并不向维护您的代码的任何人暗示您正在返回一些有用的东西。

one of the reasons I'm asking this is because I need to perform some loops on an async function so promises and await operators are involved, I remember that forEach() loops are not ideal on an async function, but wanted to know why.

forEachmap 都不会 await 如果你传递给它的函数 returns 一个承诺(async 函数做)。

所以这里有三种可能的情况:

// Your loop
...myItemsArray...
// Code that comes after the loop
...etc...

A: 循环中的项需要顺序处理

使用常规 for () 循环,因为外部函数不会暂停。

B:循环中的项可以并行处理,后面的代码不需要等待

使用 forEach.

C: 后面的代码需要等待循环中的所有内容完成

使用 map。将返回的承诺数组传递给 Promise.all。然后await那个。