问题描述:

I have an array of objects such as: (however my real array is 13000 long)

var items = [

{

name: "cat",

id: "1"

},

{

name: "dog",

id: "2"

}

];

I am trying to iterate over the objects until an object with name is found

however I get maximum call size exceeded when using this large array (13000 size), if I use the array above I get no error.

async code:

function getItemIdByName(itemName, done) {

async.detect(

items,

function hasItemName(item, cb) {

return cb(null, item.name === itemName);

},

function(err, result) {

if (err) {

return done(new Error(err));

}

if (_.isUndefined(result)) {

return done(new Error("Item not found"));

}

done(null, result);

});

};

getItemIdByName('Dog', function foundItem(err, itemId) {

console.log("got error", err);

console.log("got item", itemId);

});

I get the correct output in the console

got error null

got item { id: 2, name: 'dog' }

however I also get RangeError: Maximum call stack size exceeded

How can I make this work with my large array of objects?

网友答案:

Your "iteratee" is synchronous, which is causing the stack exhaustion problem (basically, it's processing all the items in the same "tick", using the same stack frame).

If you want to test your code with a synchronous test setup, you can use async.ensureAsync() to make sure that the iteratee becomes asynchronous:

async.detect(
  items,
  async.ensureAsync(function hasItemName(item, cb) {
    return cb(null, item.name === itemName);
  }),
  ...
);
相关阅读:
Top