Sololearn: Learn to Code
New course! Every coder should learn Generative AI!
Try a free lesson
+ 3
Good morning! This sounds like a mix beteen map and filter. If you insist on running the tasks in parallel (which is fine), then I would do it like this: let promises = myArray.map(some_async_task); let results = await Promise.all(promises); And then either for(let result of results) if(result) some_action(result); or results.filter(x => x).map(some_action); if you need the return values. Hope that helps!
22nd May 2019, 6:31 AM
Schindlabua
Schindlabua - avatar
+ 2
rudolph flash In the first case, the splice never happens, you can see this with a console.log after line 23. In the second case, with each splice, the array is being modified, this can be seen with console.log(JSON.stringify(arr)) after line 40.
21st May 2019, 8:18 PM
ODLNT
ODLNT - avatar
+ 2
rudolph flash My knowledge of async-await is limited at best... This may shed some light on the inner workings https://javascript.info/async-await
21st May 2019, 8:34 PM
ODLNT
ODLNT - avatar
+ 2
`.forEach` is just a for loop right. If you run for(let x of things){ function_that_returns_promise(x); } Then all the `things` will run "in parallel" because the function probably returns immediately, but we don't wait for the promise to resolve. So the for loop behaves like you would expect it to: Run the loop body, do the same thing for the next element, and the next... It's like for(let x of things){ function_that_returns_number(x); } but it's not a number but a promise. In your case that means that the loop spawns all five promises before the first `await` is done awaiting, because setting up and resolving a promise takes a bit of time but running a for loop is really cheap. That being said you shouldn't slice an array you are currently looping through, especially if async/await is involved. It's totally possible that a promise resolves before the for loop is done looping and then anything can happen.
21st May 2019, 10:04 PM
Schindlabua
Schindlabua - avatar