Async loops, and why they fail! Part 2

More problems with async calls and loops in JavaScript; how to handle mapping and filtering.

Federico Kereki
Jan 14 · 5 min read

Mapping — a manual solution

19:58:20.008 START -- using map(...) 
19:58:20.009 END
Result of map: [
Promise { <pending> },
Promise { <pending> },
Promise { <pending> },
Promise { <pending> },
Promise { <pending> }
]

19:58:21.010 data #1
19:58:23.011 data #3
19:58:25.010 data #5
19:58:28.013 data #8
After awaiting:  [ 
{ status: 'fulfilled', value: 'data #1' },
{ status: 'rejected', reason: 'FAILED' },
{ status: 'fulfilled', value: 'data #3' },
{ status: 'fulfilled', value: 'data #5' },
{ status: 'fulfilled', value: 'data #8' }
]
Final: [ 'data #1', undefined, 'data #3', 'data #5', 'data #8' ]

Mapping — a better solution

20:24:57.971 START -- using .mapAsync(...) method 
20:24:57.974 Calling - v=1 i=0 a=[1,2,3,5,8]
20:24:57.975 Calling - v=2 i=1 a=[1,2,3,5,8]
20:24:57.975 Calling - v=3 i=2 a=[1,2,3,5,8]
20:24:57.975 Calling - v=5 i=3 a=[1,2,3,5,8]
20:24:57.975 Calling - v=8 i=4 a=[1,2,3,5,8]
20:24:58.977 Success - data #1
20:24:59.977 Failure - error
20:25:00.976 Success - data #3
20:25:02.976 Success - data #5
20:25:05.979 Success - data #8
20:25:05.979 END -- [data #1,,data #3,data #5,data #8]

Filtering

20:39:15.237 START -- using .filterAsync(...) method 
20:39:15.241 Calling - v=1 i=0 a=[1,2,3,5,8]
20:39:15.241 Calling - v=2 i=1 a=[1,2,3,5,8]
20:39:15.241 Calling - v=3 i=2 a=[1,2,3,5,8]
20:39:15.241 Calling - v=5 i=3 a=[1,2,3,5,8]
20:39:15.241 Calling - v=8 i=4 a=[1,2,3,5,8]
20:39:16.244 Success - true
20:39:17.243 Failure - error
20:39:18.243 Failure - error
20:39:20.243 Success - true
20:39:23.242 Success - false
20:39:23.242 END -- [1,5]

Summary

References

DailyJS

JavaScript news and opinion.

Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore

If you have a story to tell, knowledge to share, or a perspective to offer — welcome home. It’s easy and free to post your thinking on any topic. Write on Medium

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store