Skip to content

Commit 1ea1193

Browse files
committed
Initial commit
1 parent 9b8233c commit 1ea1193

File tree

2 files changed

+16
-19
lines changed

2 files changed

+16
-19
lines changed

async.go

Lines changed: 8 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,6 @@ package async
88
type Task func() interface{}
99
type Channel chan interface{}
1010
type Result []interface{}
11-
type Out interface{}
1211

1312
type Promise struct {
1413
//TODO:
@@ -19,27 +18,19 @@ type Promise struct {
1918
}
2019

2120
func (p *Promise) All(tasks []Task) Result {
22-
workers := make([]Channel, 0, len(tasks))
21+
// buffer channels for go routines
22+
workers := make(Channel, len(tasks))
23+
defer close(workers)
2324
for _, task := range tasks {
24-
result := execute(task)
25-
workers = append(workers, result)
25+
go func(task Task) {
26+
workers <- task()
27+
}(task)
2628
}
2729

2830
// gather data from all channels
2931
out := make(Result, 0, len(tasks))
30-
for _, a := range workers {
31-
out = append(out, <-a)
32-
}
33-
return out
34-
}
35-
36-
func execute(task Task) Channel {
37-
out := make(Channel)
38-
{
39-
go func() {
40-
defer close(out)
41-
out <- task()
42-
}()
32+
for i := 0; i < len(tasks); i++ {
33+
out = append(out, <-workers)
4334
}
4435
return out
4536
}

examples/main.go

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -13,16 +13,22 @@ func main() {
1313

1414
tasks := []async.Task{
1515
func() interface{} {
16-
time.Sleep(1000 * time.Microsecond)
16+
fmt.Println("Running Hello..........")
17+
time.Sleep(4 * time.Second)
18+
fmt.Println("Completed Hello..........")
1719
return "Hello"
1820
},
1921
func() interface{} {
20-
time.Sleep(100 * time.Microsecond)
22+
fmt.Println("Running World..........")
23+
time.Sleep(2 * time.Second)
24+
fmt.Println("Completed World..........")
2125
return "World"
2226
},
2327
}
2428

29+
fmt.Println("From: ", time.Now())
2530
result := promise.All(tasks)
31+
fmt.Println("End: ", time.Now())
2632

2733
fmt.Println("Result: ", result)
2834

0 commit comments

Comments
 (0)