I have a project where I need to write a function to calculate several things sequentially and then write the results to a SQL DB. Unfortunately, I need to repeat this over 40,000 times. I use node.js and promises to accomplish this but the memory usage goes to almost 2GB a lot of times the program just dies after 10,000 or so calculations. I developed my own native promiseEach function which takes a array items sequantially and chains it with promises.
What Am I doing wrong here?:
function promiseEach(array,promiseFn){
return new Promise(function(resolve,reject){
try {
var promiseArray = [];
var json = { array: array, counter: 0 }
for (var i = 0; i < array.length; i++) {
promiseArray.push(promiseFn)
}
promiseArray.reduce(function(preFn,curFn,index,pArray){
return preFn
.then( function(z){ return json.array[json.counter++] })
.then(curFn)
},
Promise.resolve(json.array[json.counter]))
.then(resolve,reject)
}catch(err){
console.log("promiseEach ERROR:");
reject(err)
}
})
}