Skip to content

add a Poll function to node promises #34

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 24 additions & 8 deletions promise.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,19 +4,21 @@ 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{}),
ctx: ctx,
}
}

// 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
Expand All @@ -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.
Expand All @@ -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.
Expand All @@ -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.
Expand Down