Last active
February 16, 2018 17:13
-
-
Save dheffx/8cc8bbedb020cd83d7d78ce85ce3ffa1 to your computer and use it in GitHub Desktop.
an example of a promises in go, though i think i wrote this while following a tutorial, i cant remember tbh
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"errors" | |
"fmt" | |
"time" | |
) | |
func main() { | |
po := new(PurchaseOrder) | |
po.Value = 4.20 | |
SavePO(po, false).Then(func(obj interface{}) error { | |
po := obj.(*PurchaseOrder) | |
fmt.Printf("Purchase Order Saved: %d\n", po.Number) | |
return nil | |
}, func(err error) { | |
fmt.Printf("Failed to save purchase order:" + err.Error() + "\n") | |
}).Then(func(obj interface{}) error { | |
fmt.Println("Second Promise success") | |
return nil | |
}, func(err error) { | |
fmt.Println("Second promise fail") | |
}) | |
fmt.Scanln() | |
} | |
type PurchaseOrder struct { | |
Number int | |
Value float64 | |
} | |
func SavePO(po *PurchaseOrder, shouldFail bool) *Promise { | |
result := new(Promise) | |
result.successChannel = make(chan interface{}, 1) | |
result.failureChannel = make(chan error, 1) | |
go func() { | |
time.Sleep(2 * time.Second) | |
if shouldFail { | |
result.failureChannel <- errors.New("Failed to save") | |
} else { | |
po.Number = 1234 | |
result.successChannel <- po | |
} | |
}() | |
return result | |
} | |
type Promise struct { | |
successChannel chan interface{} | |
failureChannel chan error | |
} | |
func (this *Promise) Then(success func(interface{}) error, failure func(error)) *Promise { | |
result := new(Promise) | |
result.successChannel = make(chan interface{}, 1) | |
result.failureChannel = make(chan error, 1) | |
timeout := time.After(1 * time.Second) | |
go func() { | |
select { | |
case obj := <-this.successChannel: | |
newErr := success(obj) | |
if newErr == nil { | |
result.successChannel <- obj | |
} else { | |
result.failureChannel <- newErr | |
} | |
case err := <-this.failureChannel: | |
failure(err) | |
result.failureChannel <- err | |
case <-timeout: | |
failure(errors.New("Timed Out")) | |
} | |
}() | |
return result | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment