Closed lijams closed 4 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;
@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()
});
oh, of course. I've never thought of nesting the returns like that without a wrapper promise. Nice.
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.
yeah of course, it had just never clicked like that. This should clean up a lot of my code :)
Closing this issue because it looks like the original question was resolved.
I want to break from then, because of some conditions
Foo() .Then(result=>{ if (!result) { return .... (how to exit from here?) } return Bar() }) .Then(...)