Synchronous Code In Then Handler Of Promise
Solution 1:
Does this 'pattern' for executing synchronous code after a promise is resolved make sense?
Yes. That's what we all do.
Is it okay to return
undefined
from thethen
block?
Not really, every work should have a result (otherwise it would be pointless) and you should return
that. But if your function is only executing side effects, then returning undefined
is the result, so it's okay.
What happens if someone decides to implement
synchronousFunc1
with a promise? This will break the order of execution.
Yes, that's a breaking change.
I think such a breaking change shouldn't be made. Instead another
asynchronousFunc1
should be implemented. Am I right?
How breaking changes are handled depends on the policy of the library and its contracts with callers. It might be a major version update, it might be a new function, it might be anything; it should be announced properly of course. You'll have to change your code anyway.
If the name of the function suggests that it's synchronous, it shouldn't return a promise; the name should be changed with the implementation in that case.
What about my
catch/then
implementation? The finalthen
should be executed always. I think this will not work, if an exception is thrown in thecatch
handler.
Correct. You'll have to make sure that the catch
handler doesn't throw :-)
Are there alternatives? I know there is a
finally
handler in bluebird, but I want to use standard Promise features only.
If you are using bluebird, you should use finally
. It'll likely become standardised anyway, and many other libs support it as well. If not, you can always shim it yourself. Its implementation is superior to yours, especially about return values and handling things like cancellation appropriately.
Post a Comment for "Synchronous Code In Then Handler Of Promise"