Sunday 18 March 2018

Learning Promises and Reduce, Map Functions Cut My Code In Half

I've been a web developer since I was a teenager, and I started learning node last year to build a cloud-based data platform on GCP. Over the last year I've forced myself to start learning about promises... For some reason, this concept took me a long time to "get".Recently, I've started rebuilding some of my essential functions, and comparing my old code, realized how much promises help.All of my code that requires synchronous data transfer and analysis has been cut in half, and way simplified. I used to have these crazy nested recursive functions with callbacks to set off the next event.Now it's just a few basic chained promises. As if cutting the code in 1/2 wasn't enough, reading it is now 10x easier too. Reduce was pretty critical to getting all my arrays of data to process synchronously, which further simplified things.Anyways, if you have not learned promises, reduce, map functions yet, I highly recommend it!Just the gist of what I'm talking aboutlet myArray = ["beans", "soup", "peanuts", "artichokes"]; myArray.reduce((promise, item) => { return promise.then(() => { return itemsPromise(item); }); }, Promise.resolve()).then(() => { console.log("ALL DONE"); }) let itemsPromise = (item) => { console.log("Item: ", item); return new Promise((resolve, reject) => { setTimeout(() => { resolve(); }, 2000); }); } I'm really excited about this!!

Submitted March 18, 2018 at 11:43PM by boon4376

No comments:

Post a Comment