chebyrash / promise

Promise / Future library for Go

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Range over promise.All

metehus opened this issue · comments

So, i'm working on something like this:

artists, err := promise.All(promises...).Await()

for _, artist := range artists {
    doSomethingWith(artist)
}

But, because .Await() returns a interface{}, i can't range through it
image

I also tried to specify the type:

var artists []*structs.ArtistResponse
artists, _ = promise.All(promises...).Await()

for _, artist := range artists {
    doSomethingWith(artist)
}

But then, i receive this:
image

I'm using Go 1.15

commented

Hi @metehus

Right now the best you can do is something like this:

type Artist struct {
	Name string
}

func getArtist(name string) *promise.Promise {
	return promise.Resolve(Artist{Name: name})
}

func doSomethingWith(artist Artist) {
	fmt.Println(artist.Name)
}

func main() {
	artists, _ := promise.All(
		getArtist("aaa"),
		getArtist("bbb"),
		getArtist("ccc"),
	).Await()

	for _, a := range artists.([]interface{}) {
		doSomethingWith(a.(Artist))
	}
}

This is because .Await() returns interface{} type since Go doesn't support generics (yet)

Oh cool, that worked, i also casted it into the range already

	for _, artist := range artists.([]*structs.ArtistResponse) {
		doSomethingWith(artist)
	}

Thank you so much!