Real-Serious-Games / C-Sharp-Promise

Promises library for C# for management of asynchronous operations.
MIT License
1.19k stars 149 forks source link

How to exit from then when check some conditions #101

Closed lijams closed 4 years ago

lijams commented 5 years ago

I want to break from then, because of some conditions

Foo() .Then(result=>{ if (!result) { return .... (how to exit from here?) } return Bar() }) .Then(...)

adamsingle commented 5 years ago

If you're trying to "return" asynchronously then you realistically need the method to return a promise and then you can conditionally resolve or reject the top level one.

var promise = new Promise();

Foo()
.Then( result => 
{
    if (!result)
    {
        promise.Reject(new Exception("message here"));
    }
    else 
    {
        Bar()
        .Then(() => 
            promise.Resolve())
        .Catch(ex => promise.Reject(ex)); //if you want this to reject your top level promise
    }
});

return promise;
RoryDungan commented 5 years ago

@adamsingle is right, either returning some other value like null or rejecting a promise are the two ways you can exit early. You can basically think of a promise as a function that runs asynchronously, and can either "resolve" to return a value or "reject" to throw an exception.

That said, you don't need to call promise.Reject directly to reject a promise - just throwing an exception inside a Then callback will do. Here's a more simplified example that should do the same thing as @adamsingle's code above.

return Foo()
    .Then(result => 
    {
        if (!result)
        {
            throw new Exception("message here");
        }
        return Bar()
    });
adamsingle commented 5 years ago

oh, of course. I've never thought of nesting the returns like that without a wrapper promise. Nice.

RoryDungan commented 5 years ago

Yeah so if Bar() returns a promise, returning that inside a .Then callback will resolve the outer promise when Bar() resolves or reject it when Bar() rejects.

adamsingle commented 5 years ago

yeah of course, it had just never clicked like that. This should clean up a lot of my code :)

RoryDungan commented 4 years ago

Closing this issue because it looks like the original question was resolved.