I have a question, even though this blog post is about Node.js, I have a question about Go.
How can you mimic Promise.all() in Go? What would be equivalent code in Go?
asyncfunctionmain(){// Assume all db calls will return a promiseconstfirstUserPromise=firstDbCall().then((res)=>res);constsecondUserPromise=secondDbCall().then((res)=>res);constthridUserPromise=thridDbCall().then((res)=>res);const[firstUserData,secondUserData,thirdUserData]=awaitPromise.all([firstUserPromise,secondUserPromise,thirdUserPromise]);}
This is the example you can find in the documentation link:
packagemainimport("sync")typehttpPkgstruct{}func(httpPkg)Get(urlstring){}varhttphttpPkgfuncmain(){varwgsync.WaitGroupvarurls=[]string{"http://www.golang.org/","http://www.google.com/","http://www.somestupidname.com/",}for_,url:=rangeurls{// Increment the WaitGroup counter.wg.Add(1)// Launch a goroutine to fetch the URL.gofunc(urlstring){// Decrement the counter when the goroutine completes.deferwg.Done()// Fetch the URL.http.Get(url)}(url)}// Wait for all HTTP fetches to complete.wg.Wait()}
I have a question, even though this blog post is about Node.js, I have a question about Go.
How can you mimic
Promise.all()
in Go? What would be equivalent code in Go?funny enough, in Go is a little bit harder to do the exactly same!
i recommend you to go through two blog posts:
you will need to use channels/goroutines to achieve the same.. as said by rhymes in this thread, you will need to use WaitGroup!
there's a
merge
function in the documentation link of item 1 above, where using it, you can do something like this:running it will print:
i've been using it since I discovered it :)
I think you can also use errgroup to handle errors gracefully
This looks simple and powerful. Probably I'll have to dig deeper to understand it. Thanks for the resources.
You probably need to use a WaitGroup.
This is the example you can find in the documentation link:
WaitGroup is awesome 🎉
I was not aware of
WaitGroup
. Thanks!