0

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.

9
  • populateResults isn't an async function, it's just an ordinary function so it will execute completely before you even push it into promises which despite its name doesn't contain any promises. Try again with an actual async function that returns a Promise and you may see a different result. Commented Jul 21, 2017 at 8:35
  • Did you try closure? Example: jsfiddle.net/8n00zre7 Commented Jul 21, 2017 at 8:37
  • Look at SimpleJ's answer here stackoverflow.com/questions/24924038/… He uses setTimeout() Commented Jul 21, 2017 at 8:42
  • 1
    Promise.all already 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? Commented Jul 21, 2017 at 8:52
  • 1
    @KristjanKica : no, the functions are running in a parallel way, it's just that you can't see that because you are calling the result just once. jsfiddle.net/8ybzu0pz here is an example that may give you a clearer idea of what is happening: all the promises are being started in a parallel way. I'm handling a generic for each callback which proves that they all are executed in a parallel way. If you want them to be executed sequentially and make one to start after each other, then that's another situation. It may be helpful to understand exactly what you need. Commented Jul 21, 2017 at 9:05

1 Answer 1

0

An async function in Javascript is one that immediately returns a Promise and at some future point completes running.

Unlike C or Java, Javascript is only single threaded, so don't mistake an async function for one that runs in a separate thread: all of the code runs in the same thread, so completely sequentially. All you can do in an async javascript function is delay doing the work until some time later.

That means async functions are useful for code that fetches some remote data, or has a timeout, or waits for an event from the user before continuing.

You could simulate an asynchronous function here by using setTimeout:

function delayedPopulateResults(index, number) {
    return new Promise(function(resolve) {
        setTimeout(function() { resolve(populateResults(index, number); },
            Math.random());
    });
}

Now if you call delayedPopulateResults instead of populateResults your second block of code will create all the promises and log the results when completed. But remember all that does is introduce a random delay before the code executes: so the calls to populateResults() will execute in random order, but still each one has to complete before the next one runs.

If you can use the latest versions of Ecmascript (ES7) then you can use the async and await keywords to simplify this, but to run the code in your browser you probably need to use a transpiler such as Babel or Typescript to render the code in ES5.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.