0

I want to run a loop parralel. What is the best practise to handle this? At this moment it is not working parralel, so it takes over sometimes 3 seconds before the fields have been proceeded by the default loop. Below my current example;

const getData = async (method, componentDispatch, componentFields, pageNumber = 1) => {

  // It is necessary to wait for this call.
  await store.dispatch(Actions[componentDispatch], componentInit.value.currentId).then(async () => { 
    
    const fields = JSON.parse(componentFields);

    // I want to create a loop here which does NOT wait on each other, as in this loop there are other async functions, I want to run this loop next to each other on the same time.
    for (let i = 0; i < fields.length; i++) { 
      const test = await hello();
    }
  })
}
nhatimme
  • 383
  • 3
  • 19
  • Technically, all you need to do is `const test = await hello();` -> `const test = hello();` however, it seems you've removed too much code. I would assume you need the `test` variable for something. It's hard to give an exact suggestion for incomplete code. *In general* you should probably use `Promise.all()` See:[Use async await with Array.map](https://stackoverflow.com/q/40140149) and [Using async/await with a forEach loop](https://stackoverflow.com/q/37576685) – VLAZ Apr 05 '22 at 12:55
  • Just to add to the previous comment, javascript is single threaded for the most part. if you're crunching numbers, that'll still halt any other execution. Another option would be to hand off the processing to a web worker – Pellay Apr 05 '22 at 12:58
  • It's about this loop: `for (let i = 0; i < fields.length; i++) { }` as fields.length has more items in it, and have different awaits further in the loop as you can see `const test = await hello();`. I just want that if there are 4 items to loop in `fields`, they run parralel. – nhatimme Apr 05 '22 at 13:06

0 Answers0