【问题标题】:Why async.map returns multiple copies of array?为什么 async.map 返回多个数组副本?
【发布时间】:2021-01-05 00:40:45
【问题描述】:
const async = require('async');

const arr = [
    { name: 'john', id: '1' },
    { name: 'Andrie', id: '2' }]

let collectArr = [];
let data = async.mapLimit(arr, 5, async function (input) {

    collectArr.push({ name: input.name, id: input.id });
    return collectArr;
})

data.then((result) =>{
    console.log('success',result);
}).catch(e => console.log('err'));

因此,我在这里向 async.mapLimit 提供数组,而无需回调并在这里期待承诺。 预期输出:- [ { name: 'john', id: '1' }, { name: 'Andrie', id: '2' } ] ,

得到结果:-

[ [ { name: 'john', id: '1' }, { name: 'Andrie', id: '2' } ], [{名称:'约翰',id:'1'},{名称:'Andrie',id:'2'}]]

所以我的问题是它为什么要创建多个数组副本,如何处理?

【问题讨论】:

    标签: javascript node.js asynchronous async-await async.js


    【解决方案1】:

    当您只想返回新对象时,您会不必要地返回一个子数组,并且每次迭代都引用同一个数组。

    let data = async.mapLimit(arr, 5, async function (input) {
        return { name: input.name, id: input.id };   
    });
    

    不知道为什么你需要它是异步的

    【讨论】:

    • 您能否提供一些关于异步的指南,因为我无法在描述所有信息的地方找到它。官方文档不是很好
    • 我从未使用过这个库,但概念与 Array#map() 相同,限制参数略有不同
    • 好的,我去看看地图看看
    猜你喜欢
    • 1970-01-01
    • 2020-01-18
    • 2021-04-13
    • 2021-06-14
    • 1970-01-01
    • 2019-01-18
    • 1970-01-01
    • 2012-08-26
    • 2019-09-09
    相关资源
    最近更新 更多