为什么 async.map 返回数组的多个副本?

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' } ], [ { name: 'john', id: '1' }, { name: '安德烈', id: '2' } ] ]


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


Smart猫小萌
浏览 102回答 1
1回答

幕布斯7119047

您不必要地返回一个子数组,并且每次迭代都引用相同的数组,而您只想返回新对象。let data = async.mapLimit(arr, 5, async function (input) {     return { name: input.name, id: input.id };    });不确定为什么需要异步
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript