首页 > 解决方案 > difference between async array.map() and async npm package

问题描述

[Context]
I had a loop here, that I will have 760000 interations, so I'm trying to optimize it.

[Question]
In my loop, i'm using a async array.map() function

cells.map(async (cell) => {
        if (cell[0] === '!') continue;
        [...]//so much code here
        return someObj;
}

I saw the async package but I don't know what is faster, an "async map" function or the "async" package?

Please, if you can, explain the way one is faster then other.

标签: javascriptnode.jsasynchronousasync.js

解决方案


异步代码

你听说过承诺吗?如果您认为您的映射将花费太长时间并且您想要执行不需要该数组结果的以下代码,即独立代码,那么您可以使用promise 包装它以更改执行流程。

const heavyMapping = arr => Promise.resolve(
    arr.map(cell => {
        if (cell[0] === '!') continue;
        [...]//so much code here
        return someObj;
    })
);

//Call the function.
heavyMapping(arr).then((result) => processResult(result));
//Rest of your program
foo();
bar();

所以执行将是这样的:heavyMapping -> foo -> bar ... -> processResult. 如果您在没有异步代码的情况下运行代码,它将是heavyMapping -> ... -> processResult -> foo -> bar. 请注意,如果您使用的是异步代码,这并不意味着您的代码将并行执行,因为这是并发编程和并行性,这是并发的一种特殊情况,您有足够的硬件来同时执行这两个任务. 阅读更多相关信息:https ://medium.com/@deepshig/concurrency-vs-parallelism-4a99abe9efb8 。无论如何,如果您不想阻止执行foo并且bar您可以使用承诺或aync/await面对这个问题。

地图

我建议您在这种特殊情况下使用forEach而不是使用和链接。为什么?让我解释一下:mapfiltermap

  1. Map当您想要转换原始数据以获取数组中的结果时,使用方法。例如,假设您有一个名为people包含具有以下格式的对象的数组:{name: 'X', lastName: 'Y', age: 23 }并且您想要将nameand的串联lastName作为fullName属性,那么您可以使用map如下people.map(person => { fullName: `${name} ${lastName}` });
  2. 另一方面,假设您要筛选年龄至少为 18 岁的人的数据。您可以filter为此使用:people.filter(person => person.age > 18);.

在您的特定情况下,您可以使用以下链接的方法:

arr
.filter(cell => cell[0] ===  '!')
.map(/*so much code here*/);

请注意,如果您的代码块(这里有这么多代码)与数据转换无关,我鼓励您使用forEachchained tofilter而不是map.

抱歉,如果我不理解您的问题,但这就是我对此的解释。快乐编码。

PS:如果你不知道`${expression}`,它被称为模板字符串


推荐阅读