I have a two nested forEach loops, i tried using standard forEach and some own logic but it failed, than i tried the async library from npm with the code bellow:
function addValue(data, callback){
var final_data = [];
data.forEach(element => {
final_data.push(element);
});
var values =
[[1,0],
[2,0],
[3,0],
[-1,0],
[-2,0],
[-3,0],
[1,1],
[2,1],
[3,1],
[-1,1],
[-2,1],
[-3,1]];
async_.forEachOf(final_data, (item, {}, callback1) => {
values.forEach(value=>{
var obj = Object.assign({},item);
obj.x+=value[0];
obj.y+=value[1];
final_data.push(obj);
});
callback1();
}, err => {
if (err) console.error(err.message);
// Here i get different values for separate executions with same data
console.log(final_data.length)
});
}
What i am trying to achieve is that final_data is an array of objects, the first forEachOf loop should iterate through the final_data object and for each of them should run the second nested forEach creating a new object with modified values and pushing it back in the final_data array of object. The problem i am encountering is that the function always returns at a different time, hence the lenght of the final_data is always different, once 100 objects get pushed, once 670. So basically the callback in the main function which is addValue should be called once all of the objects are processed and the two for loops finish...
Using non-async code end up in infinite loop, strange
function addValue(data, callback){
var final_data = [];
data.forEach(element => {
final_data.push(element);
});
var values =
[[1,0],
[2,0],
[3,0],
[-1,0],
[-2,0],
[-3,0],
[1,1],
[2,1],
[3,1],
[-1,1],
[-2,1],
[-3,1]];
for(var i=0; i<final_data.length; i++){
for(var j=0; j<values.length; j++){
var obj = Object.assign({},final_data[i]);
obj.x+=values[j][0];
obj.y+=values[j][1];
final_data.push(obj);
console.log(final_data.length)
}
}
}
EDIT 2: Using forEach with no async works... What might be the cause of the infinite standard loop, versus the forEach ?
asynccode here, so is there any reason your trying to doasynccoding.?