I have never (intentionaly!) worked with async functions in javascript.
I have to do an assignment that requires I use async functions for elements of an array (ie for(let i=0;i<array.length;i++){do_Something_Async_here()} ) to proccess them in PARALLEL.
I have tried using setTimeout like this
unique.forEach(function (number, index)
{
setTimeout( populateResults(index,number), 0 );
});
function populateResults(index,number)
{
alert("populating results: index:"+index+" number:"+number);
var jp;
for(var i=0;i<1000000;i++)
{
jp=Math.pow(2,100);
}
alert("results populated: index:"+index+" number:"+number);
return jp;
}
and like this
let promises = [];
for (var i=0;i<unique.length;i++) {
promises.push(populateResults(i,unique[i]));
}
Promise.all(promises).then(function(results){
console.log(results);
}).catch(function(err) {
// handle error here
});
I actually do something with the number and index, but I've simplified it here. Now, when I run the code, in both cases, it seems like i normally execute code in C or java. Sequentially. What am i missing? How to make them run in parallel? Thanks in advance.
populateResultsisn't an async function, it's just an ordinary function so it will execute completely before you even push it intopromiseswhich despite its name doesn't contain any promises. Try again with an actual async function that returns aPromiseand you may see a different result.setTimeout()Promise.allalready resolves ALL the promises asyncronously in a parallel way, it just returns whenever all the promises are done, but it actually do perform all the elements in a parallel way. What are you exactly not getting from your code? do you want a callback for each promise executed and want to execute all the promises in parallel?