| // Copyright 2015 The Vanadium Authors. All rights reserved. |
| // Use of this source code is governed by a BSD-style |
| // license that can be found in the LICENSE file. |
| |
| // Utilities for running tasks asynchronously. |
| package util |
| |
| import ( |
| "v.io/v23/verror" |
| ) |
| |
| type Task func() error |
| type ErrorCb func(err error) |
| |
| // AsyncRun asynchronously starts task and returns a function that can be used |
| // to wait for task completion, returning the error if any. In addition, if the |
| // task returns a non-nil error, onError is called with the error. onError can |
| // be nil. ErrCanceled is ignored (treated as a nil error). |
| func AsyncRun(task Task, onError ErrorCb) (wait func() error) { |
| var err error |
| done := make(chan error, 1) |
| go func() { |
| defer close(done) |
| err = task() |
| // Ignore ErrCanceled. |
| if verror.ErrorID(err) == verror.ErrCanceled.ID { |
| err = nil |
| } |
| // Call onError if provided and err is not nil. |
| if err != nil && onError != nil { |
| onError(err) |
| } |
| }() |
| return func() error { |
| <-done |
| return err |
| } |
| } |