diff --git a/promise.go b/promise.go index 02743b0..c8c3e8d 100644 --- a/promise.go +++ b/promise.go @@ -4,12 +4,8 @@ import ( "context" ) -// NodePromise provides a promise like interface for a dag Node -// the first call to Get will block until the Node is received -// from its internal channels, subsequent calls will return the -// cached node. -// -// Thread Safety: This is multiple-consumer/single-producer safe. +// NewNodePromise constructs a NodePromise with the given context. Canceling the +// context will immediately cancel the NodePromise. func NewNodePromise(ctx context.Context) *NodePromise { return &NodePromise{ done: make(chan struct{}), @@ -17,6 +13,12 @@ func NewNodePromise(ctx context.Context) *NodePromise { } } +// NodePromise provides a promise like interface for a dag Node +// the first call to Get will block until the Node is received +// from its internal channels, subsequent calls will return the +// cached node. +// +// Thread Safety: This is multiple-consumer/single-producer safe. type NodePromise struct { value Node err error @@ -25,7 +27,7 @@ type NodePromise struct { ctx context.Context } -// Call this function to fail a promise. +// Fail fails this promise. // // Once a promise has been failed or fulfilled, further attempts to fail it will // be silently dropped. @@ -38,7 +40,7 @@ func (np *NodePromise) Fail(err error) { close(np.done) } -// Fulfill this promise. +// Send fulfills this promise. // // Once a promise has been fulfilled or failed, calling this function will // panic. @@ -51,6 +53,20 @@ func (np *NodePromise) Send(nd Node) { close(np.done) } +// Poll returns the result of the promise if ready but doesn't block. +// +// Returns nil, nil if not ready. +func (np *NodePromise) Poll() (Node, error) { + select { + case <-np.done: + return np.value, np.err + case <-np.ctx.Done(): + return nil, np.ctx.Err() + default: + return nil, nil + } +} + // Get the value of this promise. // // This function is safe to call concurrently from any number of goroutines.