Home  >  Article  >  Backend Development  >  How to return error from inside promise?

How to return error from inside promise?

WBOY
WBOYforward
2024-02-09 17:03:08980browse

How to return error from inside promise?

When writing code, we often need to deal with some possible error situations. However, sometimes we need to return an error inside a function or method so that it can be handled correctly when the function or method is called. In PHP we have several ways to achieve this. This article explains how to return errors from within promises to help developers better handle error situations.

Question content

I have a function (sendall) that if an error occurs in kgo.produce (documentation here), I want It returns error. How do I make it stop looping and return an error?

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
}

Workaround

It seems to me that you can get away with this by simply checking the "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
}

The above is the detailed content of How to return error from inside promise?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete