Home > Blockchain >  How to return an error from inside a promise?
How to return an error from inside a promise?

Time:01-27

I have a function (sendAll) that I want to make return error if something wrong happens in kgo.Produce (docs here). How can I make it stop looping and returning an error instead?

func (k *buffer) sendAll() error {
    for _, record := range k.buffer {
        kgo.Produce(ctx, &record, func(r *kgo.Record, err error) {
            if err != nil {
                fmt.Printf("record had a produce error: %v\n", err)
                
                // How do I return an error here and exit sendAll function?
                
            }
        })
    }
    return nil
}

CodePudding user response:

The right way is to return the error within the loop.

    import "fmt"

func exitForLoopWithError(err error) error {
  for i := 0; i < 10; i   {
    if err != nil {
      return err
    }
  }
return nil
}

func main() {
  err := fmt.Errorf("An error occurred")
  returnedErr := exitForLoopWithError(err)
  if returnedErr != nil {
    fmt.Println(returnedErr)
  }
}

CodePudding user response:

Seems to me like you can get away with a simple check of a "local" variable.

func (k *buffer) sendAll() error {

    var loop error

    for _, record := range k.buffer {
        if loop != nil {
            break
        }
        kgo.Produce(ctx, &record, func(r *kgo.Record, err error) {
           
            if err != nil {
                fmt.Printf("record had a produce error: %v\n", err)
                
                // How do I return an error here and exit sendAll function?
                loop = err
            }
        })
    }
    return loop
}

  •  Tags:  
  • go
  • Related