How to return error from inside promise?

WBOY
Release: 2024-02-09 17:03:08
forward
965 people have browsed it

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
}
Copy after login

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
}
Copy after login

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!

source:stackoverflow.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!